- Home /
Playing an Animation that is within a GameObject
Hi,
I'm new too scripting and have a hit a little bump when it comes to getting an animation to work. What I am doing is just creating a simple box that raises up out of the ground to make a barricade when the player enters a specific location.
So I have my Animation and it's attached to the Box, but I attempt to move the Box the animation with reset the Box back to the origin (where I animated). To fix this I've placed the box in a new GameObject titles Animated_Cube.
How do I in script tell the Box within Animated_Cube to play? Right now my script looks at Animated_Cube and says there's no animation attached and gives an error.
//Apply to Object that triggers animation
//Animated Object and it's Animation var raiseableGate : GameObject; var gateAnimation : AnimationClip;
function OnTriggerEnter () {
//Removes object that triggered Animation
Destroy(gameObject);
//Plays Animation on the specified GameObject
raiseableGate.animation.Play ("gateAnimation");
}
Any help would be much appreciated!
Answer by duck · Oct 11, 2010 at 09:29 AM
Ok, it sounds like your problem here is that your animation is not on the "raiseableGate" object, but on a child of that object, right?
In that case - and if it's safe to make the assumtion that the animated object is the only child object of "raiseableGate" - you can use "GetComponentInChildren" to find the correct object, like this:
//Plays Animation on the specified GameObject
var animationObj = raiseableGate.GetComponentInChildren(Animation);
animationObj.Play("gateAnimation");
The "GetComponentInChildren" command returns the first found occurrence of that component, so this is why it needs to be the only animated child object - otherwise you'd have to work out which object you wanted before calling Play().