- Home /
How to open individual prefab doors
Hello, in my game I'm trying to make it so that the player can move the crosshair over an object (in this case a footlocker), have the crosshair change color and on the press of a button have it open or close. I made the footlocker a prefab so I have a lot of them in the scene. How do I make it so that I only open the footlocker the player is looking at? Here is my code so far.
using UnityEngine;
using System.Collections;
public class ActionButtonScript : MonoBehaviour
{
int i = 0;
public float playerReach = 5.0f;
void Update ()
{
CrossHairScript crossHairScript = GetComponent<CrossHairScript>();
ChestOpenerScript chestOpenerScript = GetComponent<ChestOpenerScript>();
RaycastHit target = new RaycastHit();
Vector3 fwd = transform.TransformDirection(Vector3.forward);
Debug.DrawRay(transform.position, fwd,Color.red);
if (Physics.Raycast(transform.position, fwd, out target, playerReach))
{
if(target.collider.gameObject.tag == "Openable Door")
{
crossHairScript.x = 1; //Changes color of crosshair;
if(Input.GetKeyDown(KeyCode.E))
{
// opens the footlocker player is aiming at
}
}
else
{
crossHairScript.x = 0; //Reverts crosshair to default;
}
}
}
}
Thank you in advance
Answer by justinl · Oct 08, 2012 at 04:22 PM
I just implemented a door today. I'd recommend doing something like having a box collider on each door (is Trigger). When the player enters the box collider trigger, set a boolean "isBesideDoor" = true and when the player leaves the trigger, set that boolean to false. Then when the user presses KeyCode.E, only open the door if isBesideDoor == true;
This way, the door will only open if the player is beside it. There are a handful of other ways to implement this but this is one easy way.
Your answer
![](https://koobas.hobune.stream/wayback/20220613082041im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
door opening 3 Answers
importing exporting Animation help. 1 Answer
Open and close doors by pressing 'E' 2 Answers
Opening door. 2 Answers
Trying to Open a Door 2 Answers