I’m new to scripting, so I used a script from the “Unity Game Development Essentials” book that uses a raycast to trigger a door open and close animation. As you can see there is a section of code that is commented out that originally had the script triggering the door upon collision. That part of the script worked fine and the door was opening and closing with no problem. When I modified the script to use raycasting, now nothing happens and I get the following error back.
“NullReferenceException: Object reference not set to an instance of an object PlayerCollisions.Update () (at Assets/Scripts/PlayerCollisions.js:12)”
And line 12 is:
if(Physics.Raycast (transform.position, transform.foward, hit, 5)) {
can someone please help?
private var doorIsOpen : boolean = false;
private var doorTimer : float = 0.0;
private var currentDoor : GameObject;
var doorOpenTime : float = 3.0;
var doorOpenSound : AudioClip;
var doorShutSound : AudioClip;
function Update () {
var hit : RaycastHit;
if(Physics.Raycast (transform.position, transform.foward, hit, 5)) {
if(hit.collider.gameObject.tag=="SingleDoor" && doorIsOpen == false){
currentDoor = hit.collider.gameObject;
Door(doorOpenSound, true, "Open", currentDoor);
}
}
if(doorIsOpen){
doorTimer += Time.deltaTime;
if(doorTimer > doorOpenTime){
Door(doorShutSound, false, "Close", currentDoor);
doorTimer = 0.0;
}
}
}
/*
function OnControllerColliderHit(hit : ControllerColliderHit) {
if(hit.gameObject.tag == "SingleDoor" && doorIsOpen == false) {
currentDoor = hit.gameObject;
Door(doorOpenSound, true, "Open", currentDoor);
}
}
*/
function Door(aClip : AudioClip, openCheck : boolean, animName : String, thisDoor : GameObject){
audio.PlayOneShot(aClip);
doorIsOpen = openCheck;
thisDoor.transform.parent.animation.Play(animName);
}
@script RequireComponent(AudioSource)