Pa Rö Pa Rö - 2 years ago 429
C# Question

Unity 3D Door Script

I have written a door script for big vault doors.
My problem is the following: if I assign the script to more than one door
in the scene, all doors open and close together at the same time
that one of them is touched.

using UnityEngine;
using System.Collections;

public class BigDoorScript : MonoBehaviour

private bool doorOpen = false;
private Ray ray;
private RaycastHit hit;
private float distance = 5.0f;
public GameObject door;

private void Update()
if (Input.GetKeyDown("e"))
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, distance))
if (!doorOpen)
door.transform.Translate(new Vector3(0.0f, 0.0f, 4.0f));
doorOpen = true;
door.transform.Translate(new Vector3(0.0f, 0.0f, -4.0f));
doorOpen = false;

Answer Source

All of your doors open because you're not actually checking whether or not the hit object from your Raycast is actually the door object your script is holding a reference to. Imtiaj touches on this briefly, but string compares on Game Objects are a bad idea and does not limit yourself to one object as many Game Objects an have the same name.

Therefore, any collision will open all of the doors with this script.

You want to use

if (hit.collider.gameObject == door)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download