A Better Way to do Simple Animations in Unity

Posted on: May 25th, 2015 by tdc_user
I’ve found Unity Legacy animations to be buggy; if I want to simply open a door, they do not work as advertised, though I must admit a bones-type animation, which should be even more problematic, works well. So this complaint and alternate solution is directed at those simple legacy animations like opening a door. I was teaching a class the other night and the traditional legacy animation solution worked for half of the students, and not for the other half. Then some of them changed the names of a game object to something else, then back to the original name, and suddenly it was working! That’s a little to undependable for my taste. So here is an alternate solution: Attach the following code to anything you want to trigger an animation in another game object. So the thing you attach this script to must have a collider set to Is Trigger. Then if you are going to make a door move, you need to drag the Door game object to the appropriate slot in you Inspector, and enter the values in X, Y, and Z that you want the door to move from and to. Thing to Move is the thing you want to move; rate is the speed at which you want the animation to take place. The video that shows how to use this code is here: http://www.3dcognition.com/create-a-game-with-unity-5-in-30-minutes-part-1/ var Pos1 : Vector3; var Pos2 : Vector3; var thingToMove : GameObject; var rate = 0.1; function OnTriggerEnter(col : Collider){ if (col.gameObject.tag == "Player"){ yield MoveObject(transform, Pos1, Pos2, rate); } } function MoveObject (thisTransform : Transform, Pos1 : Vector3, Pos2 : Vector3, time : float) { var i = 0.0; while (i < 1.0) { i += Time.deltaTime * rate; thingToMove.transform.position = Vector3.Lerp(Pos1, Pos2, i); yield; } }

Comments are closed.