- Home /
The question is answered, right answer was accepted
How do I disable the gameobject by script?
Currently, I have Destroy(gameObject) within a OnTriggerEnter function. However, because of this, the player is destroyed and I get this error: "MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object." How would I just disable it instead of destroying it? Or how would I check if it is null?
This is my destroy player code:
void OnTriggerEnter (Collider other) { if (other.gameObject.tag == "Floor") { return; }
if (other.gameObject.tag != "Floor") {
Destroy (gameObject);
PlayerisDead ();
}
}
This is where I get the error:
void Update()
{
if(player.transform.position.z > distance) //error here
{
InstantiateObject();
spawnDistance = player.transform.position.z + 70.0f;
distance = spawnDistance - 30.0f;
}
if (player.transform.position.z > updateScoreDistance)
{
updateScoreDistance += 10;
score += 1;
scoreText.text = "" + score;
}
}
}
Answer by KittenSnipes · Jan 26, 2018 at 01:28 AM
@S_jay1
void Update()
{
if (player != null) {
if(player.transform.position.z > distance)
{
InstantiateObject();
spawnDistance = player.transform.position.z + 70.0f;
distance = spawnDistance - 30.0f;
}
if (player.transform.position.z > updateScoreDistance)
{
updateScoreDistance += 10;
score += 1;
scoreText.text = "" + score;
}
}
}
}
If you don’t want to Destroy the gameObject you can use this instead:
gameObject.SetSctive(false);
Answer by Ginxx009 · Jan 26, 2018 at 01:24 AM
Instead of Destroying it why don't you just do it something like enable and disable.
From here :
if (other.gameObject.tag != "Floor") {
Destroy (gameObject);
PlayerisDead ();
}
To this :
if (other.gameObject.tag != "Floor") {
gameObject.setActive(false);
PlayerisDead ();
}
Hope it helps
It gives me this error UnityEngine.GameObject does not contain a definition for setActive and no extension method setActive accepting a first argument of type UnityEngine.gameobject could be found.
Follow this Question
Related Questions
MissingReferenceException 1 Answer
Pass a copy of a GameObject as variable to another script? 1 Answer
Remove dead enemies from array 1 Answer