Error with raycast


I’m close to killing myself because ive tried to get a simple raycast from my player to open a door. Difficult? It’s taken me over 24 hours.

My code:
function Update () {

	var hit : RaycastHit;
	Debug.DrawRay(transform.position, transform.forward,;
	if(Physics.Raycast(transform.position, transform.forward, hit, 300)){
		if( == "Cube"){


I have a cube that is acting as the door, named “Cube”. It has an attached script named “OpenDoor”, which contains the function “OpenIt”, which does Debug.Log(“I received the message”);, then it will play the door open animation.

Error: NullReferenceException: Object reference not set to an instance of an object
Can anyone see my time-wasting, imbecile error?

If you can solve my problem, I will let you play my horror game when it’s finished if you like :slight_smile:

if( == “Cube”){

Your raycasthit gives you a reference to the collider hit. From there you can get the gameobject and from the game object you need to get to the attached component that is your script. Once you have a reference to the script, you will be able to call any publicly visible function of that script. The above code should do what you want as long as everything is attached as you have said