Opening door.

Hello, I have this simple script of opening doors:

#pragma strict

private var guiShow : boolean = false;

var isOpen : boolean = false;

var door : GameObject;

var rayLength = 10;

function Update()
{
	var hit : RaycastHit;
	var fwd = transform.TransformDirection(Vector3.forward);
	
	if(Physics.Raycast(transform.position, fwd, hit, rayLength))
	{
		if(hit.collider.gameObject.tag == "Door")
		{
			guiShow = true;
			if(Input.GetKeyDown("e") && isOpen == false)
			{
				door.animation.Play("dooropen");
				isOpen = true;
				guiShow = false;
			}
			
			else if(Input.GetKeyDown("e") && isOpen == true)
			{
				door.animation.Play("DoorClose");
				isOpen = false;
				guiShow = false;
			}
		}
	}
	
	else
	{
		guiShow = false;
	}
}

function OnGUI()
{
	if(guiShow == true && isOpen == false)
	{
		GUI.Box(Rect(Screen.width / 2, Screen.height / 2, 100, 25), "Use Door");
	}
}

Now… I’ve put it in my character and it works etc. But I have to manually everytime change that variable door : GameObject to which door I want to open.

Could someone point me to the right way how to get this script to look itself/automatically for which door I’m looking at as now it only works for that one door as it needs to be manually changed from editor if you wanna open up another doors than that one.

Hello there,

You do not need the door variable at all.

In the Raycasting command, remember that the variable ‘hit’ will contain the information about the object that you have hit with the raycast. So, hit.collider.gameObject will refer to the door.

Basically, you should replace this:

door.animation.Play("dooropen");

with this

hit.collider.gameObject.animation.Play("dooropen");

And do the same for the close door.

//function in the doors script

var open : boolean = false;

function OpenClose()
{
	if(open)
	{
		animation.Play("dooropen");
		open = true;
	}
	else
	{
		animation.Play("DoorClose");
		open = false;
	}
}

// when you must open/close a door you call the OpenClose function of the door

if(Physics.Raycast(transform.position, fwd, hit, rayLength))
{
	if(hit.collider.gameObject.tag == "Door")
	{
		guiShow = true;
		if(Input.GetKeyDown("e") && isOpen == false)
		{
			hit.transform.SendMessage("OpenClose",SendMessageOptions.DontRequireReceiver);
			guiShow = false;
		}

	}
	else
	{
		guiShow = false;
	}
}