- Home /
Prefab animation only plays on first instance
Ive created a Prefab, which has a child object with an Animation component. In the prefabs script I have the below code which plays a walk cycle.
function Update () {
var anim = gameObject.Find("Spider Body").GetComponent(Animation);
anim.Play("Spider Walk");
}
I use the Instantiate()
function to generate instances of the prefab.
The problem is the animation only plays on the first instance of the prefab. The following instances remain static.
I've tried using an Animator component to manage my animations but it yielded the same results.
New to Unity
Answer by KnightsFan · Jun 16, 2014 at 09:19 PM
If you simply used Instantiate(), the new object will have (Clone) at the end of its name, so gameObject.Find() will return the initial object on all instances. Even if all the objects are named the same thing, gameObject.Find will return the first object, which will still be the same object being referenced from every script. You could use GetChild or FindChild, but for performance, it isn't wise to call those functions within Update.
Another option would be to attach the script running the animation directly to the animated object (that is, the child). That way you don't have to mess with referencing other objects at all, and you can simply put animation.PlayLoop("Spider Walk") within the Start function.