Home > Enterprise >  Unity GUIEditor - how can I access the sprites within my texture from code
Unity GUIEditor - how can I access the sprites within my texture from code

Time:07-09

I want to access the sprites under the png I've got selected. (Which has already been sliced in the sprite editor)

Example: Here I know how I can make my GUIEditor see I have Druid_jump selected, now I want to grab hold of the Sprite type objects Druid_Jump_0_00 until Druid_Jump_3_03 by code (without interaction of my user) so that I can set up the 4 animations for them

enter image description here

I was trying with the following code sample:

List<Texture2D> textures = new List<Texture2D>(Selection.GetFiltered<Texture2D>(SelectionMode.Unfiltered));
foreach (Texture texture in textures)
{
    if (texture != null)
    {
        string path = AssetDatabase.GetAssetPath(texture);
        string containingFolder = null;
        if (string.IsNullOrEmpty(containingFolder))
        {
            containingFolder = path.Remove(path.LastIndexOf('/'));
        }
        var importer = AssetImporter.GetAtPath(path) as TextureImporter;
        List<Sprite> currentFrames = new List<Sprite>();
        int index = 0;
        foreach (SpriteMetaData spriteMetaData in importer.spritesheet)
        {
            string[] slice = spriteMetaData.name.Split('_');
            if (slice[2] != index.ToString())
            {
                //CreateAnimation(currentFrames.Count, currentFrames);
                currentFrames = new List<Sprite>();
                index  ;
            }

// The Code works fine until here, I need the "Sprite" type object to set up the animation
            Sprite sprite = AssetDatabase.LoadAssetAtPath<Sprite>($"{containingFolder}/{spriteMetaData.name}");
            //currentFrames.Add(sprite);
            Debug.Log(sprite.name);
        }
    }
}

I was hoping Sprite sprite = AssetDatabase.LoadAssetAtPath<Sprite>($"{containingFolder}/{spriteMetaData.name}"); would get the individual Sprite, but it currently finds null, while the spriteMetaData is actually returning the correct spritenames.

CodePudding user response:

Sprite sprite = Sprite.Create(Texture2D texture, Rect rect, Vector2 pivot);

Your rect will be probably (0,0,resultionX,resulutionY), and pivot (0.5f, 0.5f)

CodePudding user response:

Considering the image was already sliced into sprites, the correct answer was using AssetDatabase.LoadAllAssetsAtPath instead, which returns an Object array and includes the sprites under the png image. The AssetDatabase.GetAssetPath function does not include those.

Once we have the object array, we loop through the objects and cast the object to the sprite type and then we are good to go.

Object[] data = AssetDatabase.LoadAllAssetsAtPath(AssetDatabase.GetAssetPath(texture));
if(data != null)
{
    foreach (Object obj in data)
    {
        if (obj.GetType() == typeof(Sprite))
        {
            Sprite sprite = obj as Sprite;
  • Related