- Home /
How to create sprite at run time?
I found the method Sprite.Create(),but it needed a rect to point out the sprite in a texture,but it's hard for me to provide that.Since i have made up the sprite in the sprite_editor,how can i just create a sprite from that?Please tell me,thank you!
Answer by orb · Sep 10, 2014 at 11:39 AM
All you need to do is create a game object and add a SpriteRenderer component, then set its image:
using UnityEngine;
public class MakeSprite : MonoBehaviour
{
public Sprite sprite;
void Start()
{
GameObject go = new GameObject("New Sprite");
SpriteRenderer renderer = go.AddComponent<SpriteRenderer>();
renderer.sprite = sprite;
}
}
To test this script: Attach this to some object, drag the sprite texture to the sprite variable in the inspector, and ensure the texture type is set to "Sprite (2D and UI)". Extract the code and adapt for your own use :)
Thank you for your answer!But my problem is that i can't drag the sprite texture to the sprite variable in the inspector.ins$$anonymous$$d, i need to get the sprite at the run time,i don't know how to get the sprite at run time ins$$anonymous$$d of dragging to it in the inspector.
Oh, then there are only two little things to do.
Add the sprite to the Resources folder, optionally inside a folder for sprites/textures
Load the sprite via a call like this:
renderer.sprite = Resources.Load("path/name")
If the sprite is directly under Resources, no path is required.
But Resources.Load("path/name") return me a Texture2D not sprite...