- Home /
"There is no 'GameObject' attached to the "x" game object'
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!
Answer by cstooch · Jun 21, 2017 at 04:17 PM
Try deleting the first two lines in your start.. you already do this in inspector, so you shouldn't need to look for any components.
Sorry ignore this follow up post.. I get what you're doing. I think just removing the lines i suggested in start should do it.
I tried this this morning (with a movement of the if(input), and it seems to be all working now!
Thank you!!
Answer by tanoshimi · Jun 21, 2017 at 10:06 PM
A gameobject is not a component, so the syntax GetComponent<GameObject>()
doesn't make any sense. Components are attached to gameobjects. Since you already have a reference to the doorOpen and doorClosed gameobjects you should just call .SetActive directly on them.
Your answer
Follow this Question
Related Questions
Is there a way to dynamically attach a script to a GameObject during runtime? 1 Answer
How to add components to other GameObjects through a C# script attached to one? 2 Answers
Can't disable component, little checkbox is missing from inspector 1 Answer
How to handle coupled components in Unity 2 Answers
Access water4 scripts via my script? 1 Answer