Making a specific door open in a dungeon with multiple doors
I've searched several different questions and can't seem to figure out my problem. I'm trying to open a specific door in a dungeon that currently has 2 doors(there will be more doors if I ever figure this out). In my PlayerController script I declared
public DoorOpen doorOpen; //reference to my DoorOpen Class
[SerializeField]private GameObject currentDoor; //reference to the door I'm trying to currently open
My open door script is:
//Door check
RaycastHit doorHit;
//GameObject currentDoor;
Debug.DrawRay (transform.position + new Vector3(0f, 1f,0f), transform.forward * 2f, Color.red);
if(Physics.Raycast(transform.position + new Vector3(0f, 1f,0f), transform.forward * 2f, out doorHit)){
if(doorHit.collider.gameObject.tag == "Door" && Input.GetKeyDown(KeyCode.R)){
print ("Open the door!");
currentDoor = doorHit.collider.gameObject; //assigns the current door
doorOpen.OpenCheck (); //runs script attached to DoorOpen class
}
}
My DoorOpen class:
public class DoorOpen : MonoBehaviour { public bool isDoorOpen = false;
public void OpenCheck(){
if(isDoorOpen == false){
isDoorOpen = true;
print ("Opened");
Vector3 to = new Vector3(0,90,0);
transform.eulerAngles = Vector3.Lerp (transform.rotation.eulerAngles, to, Time.deltaTime * 90);
}else{
isDoorOpen = false;
print ("Closed");
Vector3 back = new Vector3 (0, -90, 0);
transform.eulerAngles = Vector3.Lerp (-transform.rotation.eulerAngles, back, Time.deltaTime * 90);
}
}
}
What I'm currently getting is that in my Player Inspector window, CurrentDoor is assigning the proper door, but Door Open is remaining null. I'm thinking if I can assigned CurrentDoor to DoorOpen it should work, but when I try to do that it get "Assets/Scripts/Player/PlayerController.cs(50,17): error CS0029: Cannot implicitly convert type UnityEngine.GameObject' to
DoorOpen'" If I take out the CurrentDoor step and just assign the GameObject 'door' in the player Inspector window, it will only open that specific door and not any other door.
Answer by Commoble · Mar 15, 2017 at 06:10 PM
If you have a reference to the gameobject with the DoorOpen component on it, you can get a reference to the DoorOpen script with GetComponent. So then you can do:
doorObject = doorHit.collider.gameObject;
DoorOpen doorScript = doorObject.GetComponent<DoorOpen>();
if (doorScript != null)
{
doorScript.OpenCheck();
}
That worked perfectly. Thanks so much, I felt like I was pretty close just couldn't get the last bit figured out.
Your answer
Follow this Question
Related Questions
Learning to equip weapons etc to character but its not working! 1 Answer
Problem with game animation for gameobject movement 0 Answers
Activating a gameobject from a script attached to a different gameobject. 1 Answer
Sprite Rendering Order 1 Answer
How do i convert game object counts, into int, and put into string? 0 Answers