I have a door open/close script i have created. It works with tags.
If raycast hits object tagged with “door” it opens the door. However it opens all the doors in the scene.
Does anybody have an alternative i can try?
if (In
put.GetKeyDown (KeyCode.E))
{
print (“e was pressed”);
if (Physics.Raycast (ray, out hit, rayDistance)) //check for raycast
{
print ("Ray hit a surface");
if (hit.collider.gameObject.tag == "Door") //check for door
{
print ("ray cast on door");
//change crosshair
if (gateOpen == false) //check for key press/gate is open(Input.GetKeyDown (KeyCode.E) &&
{
print ("e was pressed to open");
gateControl ("open");
gateOpen = true;
AudioSource.PlayClipAtPoint (gateOpenSound, transform.position);
// print ("door is open");
}
else if (gateOpen == true) //check for key press2/gate
{
print ("e was pressed to close");
gateControl ("close");
gateOpen = false;
AudioSource.PlayClipAtPoint (gateCloseSound, transform.position);
What is that gateOpen and how is it related to the door?
Because i think that you are checking if the raycast hit a door, and then just opens a door, instead of accessing the door open script on that specific door that it hit.
(like hit.GetComponent.().open(); for example)
Also, it’s easier on resources if you are using collider.CompareTag(“tag”) instead of checking against a string.
Also, if (!gateOpen) is the same as if (gateOpen==false)
This line…
if (hit.collider.gameObject.tag == "Door")
Checks to see if the raycast hit a door. Any door.
But the script is on all doors. So it is effectively saying to each door, “if the raycast hit any door, open this door”. You want it to be more like “if the raycast hit this door, open this door”.
So, change it to…
if (hit.collider.gameObject == this.gameObject)
Note that the script is on a door, so having checked that the raycast has hit the current object, you don’t need to check that it’s a door.
The way you’ve done things, every door is doing the raycast for itself. An alternative way of doing things, that’s more efficient, is to do the raycast just once, in a manager object of some kind (ie there is only one of this kind of object in the scene). Then, the code would look more like what you’ve done. You would need to check that the object that’s been hit is a door, but then make that door open. Something like this in the manager object’s update function
if (hit.collider.gameObject.tag == "Door")
{
hit.collider.gameObject.GetComponent<Door>().HandleHit();
}
and a HandleHit() function in the Door script that does the opening/closing (or whatever).
Bare with me, I pretty much made this script myself and I’m new to scripting. (don’t be afraid to give me basic tips) This script is the only script used and it is attached to the door, should I instead have it on the player?
Thanks very much