I’m trying to have a script change two objects in my game between enabled and disabled, and I have a script to get the component of both of these game objects, but every time I run my game, the game objects seem to disappear from the ‘GetComponent’ section of the script, thus giving me the error that ‘There is no ‘GameObject’ attacked to the “x” game object’. I don’t know why this keeps happened, or what to do to fix it, so I was hoping that someone could point me in the right direction?
This is my script that changes the stats of the game objects:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Door : MonoBehaviour
{
public GameObject doorOpen;
public GameObject doorClosed;
public bool Collide;
public bool doorShut;
// Use this for initialization
void Start()
{
doorOpen = GetComponent<GameObject>();
doorClosed = GetComponent<GameObject>();
doorShut = true;
doorClosed.SetActive(true);
doorOpen.SetActive(false);
}
// Update is called once per frame
void Update()
{
}
void OnGUI()
{
if (Collide == true)
{
if (doorShut)
{
GUI.Label(new Rect(Screen.width / 2 - 100, Screen.height / 2 + 10, 200, 100), "Press E to Open");
}
}
}
void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
Collide = true;
if (Input.GetKeyDown(KeyCode.E))
{
doorClosed.SetActive(false);
doorOpen.SetActive(true);
doorShut = false;
}
}
}
void OnTriggerExit(Collider other)
{
if (other.tag == "Player")
{
Collide = false;
}
}
}
Here are pictures of the script before running and after running:
Not Running:
Running:
Thank you!