- Home /
Play animation with Raycast
Hi, So i'm trying to play a animation (open a chest) using raycast.
I'm trying to trigger a function called PlayForward(); with this code:
var ChestAnim : OpenChest;
function Update () {
var cam : Transform = Camera.main.transform;
var ray = new Ray(cam.position, cam.forward);
var hit : RaycastHit;
if(Input.GetKeyDown(KeyCode.F)){
Physics.Raycast (ray, hit, 30);
Debug.DrawLine (ray.origin, hit.point);
if (hit.collider.tag == "Chest"){
ChestAnim = gameObject.GetComponent("OpenChest");
ChestAnim.PlayForward();
Debug.Log("your raycast hit door");
}
}
}
And the script on the Chest is:
public var animationClip : AnimationClip;
function PlayForward()
{
animation[animationClip.name].speed = 3.0f;
animation.Play(animationClip.name);
}
function PlayBackward()
{
animation[animationClip.name].speed = -3.0f;
animation[animationClip.name].time = animation[animationClip.name].length;
animation.Play(animationClip.name);
}
I don't get any errors unitill i press "f" on the chest. Then i get "Object reference not set to an instance of an object RayCast.Update ()" anyone know what the problem is?
Thanks!
Comment
ChestAnim = gameObject.GetComponent("OpenChest");
Are you sure you didn't forget something here?
Best Answer
Answer by ExplodingCookie · Jul 06, 2013 at 02:35 AM
Your problem is on line 14
ChestAnim = gameObject.GetComponent("OpenChest");
This code links to the GameObject with this script attached to it. To access the chest, you need to use this
ChestAnim = hit.collider.gameObject.GetComponent("OpenChest");
This should solve your problem
~ExplodingCookie