Scripting Guide
Assigning Sprites to N-Slice Components
When working with N-Slicer components in your scripts, it's important to follow the correct approach for assigning sprites.
1using NSlicer.Runtime.Component;
2using NSlicer.Runtime.Core;
3using UnityEngine;
4
5public class NSlicerSample : MonoBehaviour
6{
7 [SerializeField] private NSliceImage sliceImage;
8 [SerializeField] private NSliceSpriteRenderer sliceSpriteRenderer;
9
10 private void Start()
11 {
12 // Don't assign the sprite itself.
13 sliceImage.sprite = Resources.Load<Sprite>("SomeSprite"); // DON'T DO THIS
14
15 // Instead, assign the NSliceData.
16 // This will automatically assign the sprite to the NSliceImage.
17 sliceImage.NSliceData = Resources.Load<NSliceData>("SomeSliceData");
18 }
19}
Important Notes
Warning
- Never assign sprites directly to N-Slice components via code. (on inspector, you can)
- Always work with NSliceData objects, which contain both the sprite and slicing information
- Make sure your NSliceData is properly configured before using it in runtime code
Runtime Modification
You can dynamically change the NSliceData at runtime to update the appearance of your UI elements or sprites:
1// Load different NSliceData assets based on game state
2public void ChangeAppearance(string themeName)
3{
4 NSliceData newThemeData = Resources.Load<NSliceData>($"Themes/{themeName}/ButtonData");
5 if (newThemeData != null)
6 {
7 sliceImage.NSliceData = newThemeData;
8 }
9}
This approach allows for dynamic theming and visual updates in your application while maintaining the proper slicing configuration.