Scripting Guide
How to use N-Slicer in your scripts
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.
using NSlicer.Runtime.Component;
using NSlicer.Runtime.Core;
using UnityEngine;
public class NSlicerSample : MonoBehaviour
{
[SerializeField] private NSliceImage sliceImage;
[SerializeField] private NSliceSpriteRenderer sliceSpriteRenderer;
private void Start()
{
// Don't assign the sprite itself.
sliceImage.sprite = Resources.Load<Sprite>("SomeSprite"); // DON'T DO THIS
// Instead, assign the NSliceData.
// This will automatically assign the sprite to the NSliceImage.
sliceImage.NSliceData = Resources.Load<NSliceData>("SomeSliceData");
}
}
Important Notes
- Never assign sprites directly to N-Slice components
- 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:
// Load different NSliceData assets based on game state
public void ChangeAppearance(string themeName)
{
NSliceData newThemeData = Resources.Load<NSliceData>($"Themes/{themeName}/ButtonData");
if (newThemeData != null)
{
sliceImage.NSliceData = newThemeData;
}
}
This approach allows for dynamic theming and visual updates in your application while maintaining the proper slicing configuration.