- Home /
How to set a prefab SpriteRenderer.sprite using script in editor?
I'm trying to set the sprite of a prefab in script
Texture2D texture = AssetDatabase.LoadAssetAtPath<Texture2D>(assetPath);
Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0, 0));
spriteRenderer.sprite = sprite;
The result is either sprite ends up as Type mismatch but actually works or the sprite ends up as None
What am I doing wrong? How am I supposed to create a sprite from a texture in script and apply it to a spriteRenderer?
Answer by gavin_dodd · Dec 08, 2015 at 05:33 PM
Of course within an hour of posting this I worked out my problem.
Assets can be loaded as multiple types so instead of loading as a Texture2D and creating a Sprite I needed to do this:
Sprite sprite = AssetDatabase.LoadAssetAtPath<Sprite>(assetPath);
Problem solved
Your answer
Follow this Question
Related Questions
Can we make a script an Addressable in Unity ? 2 Answers
Tower defense target update 0 Answers
Disfigured sprite after build. 0 Answers
How to use an Editor script? 0 Answers
How do I programmatically assign a GameObject to a prefab? 6 Answers