- Home /
Efficient way to instantiate a sprite that plays an animation then destroys itself? (3d space)
I'm getting a little tired of trying to piecemeal and shoe-horn different answers together, so I figured I'd see if someone would be willing to help me on my specific issue at hand.
I have a 3d scene with characters over whom I would like to display a short animation when something happens. I can create, place, and parent the object on trigger with no issue. What I am struggling with is Unity's animator system. I don't quite understand how it all works together.
The following code works great for spawning a sprite, and I could use a co-routine to destroy it after a given time if I wanted...
public static void SpawnSprite(Sprite sprite, Vector3 spawnLocation, Transform parent = null)
{
GameObject obj = new GameObject(sprite.ToString());
SpriteRenderer renderer = obj.AddComponent<SpriteRenderer>();
renderer.sprite = sprite;
obj.AddComponent<Billboard>();
obj.transform.position = spawnLocation;
obj.transform.parent = parent;
}
What I can't make sense of then is how to make it animate. I could add an animator component, but do I then need an animation component to go with that?
Ultimately I would like to be able to call the function with one string "spriteName" and not have to worry about assigning the extra things from the call. It would also be nice to avoid having 20 public 'animator' and 'animation/sprite' variables in the inspector, but I'm willing if needs be.
Thanks in advance
Answer by WbrJr · Feb 23, 2018 at 03:34 PM
I would recommand to use "Object Pooling"..
The best would be to look it up on youtube, brakeys did a video to that topic recently..
the idea is, to use serveral objects and activate them if needed. this method is a bit more efficent, because instanting and creating a new object is quite complicated..
Have a nice day and fun :)
WbrJr