I’ve got a prefab that I spawn and after using the prefab it will be destroyed Destroy (gameObject)
then after a few seconds a different game object will respawn a new prefab of the origional.
Everything works fine except when the new prefab is trying to spawn I get this message:
“MissingReferenceException: The object of type ‘GameObject’ has been destroyed but you are trying to access it. Your script should either check if it is null or you should not destroy the object”
So my question is: should I check to make sure its null and fix up the script?
OR
Should I not actually destroy the game object and instead make it become disabled (both vidually and with code) and become enabled after the timer?
What are you trying to do?
it would be helpful if you included more of your code so we can see what you are actually doing… the instantiate code and the lines where the error occur at the minimum.
I’m trying to set up a resouce gathering system, cutting down trees, mining ricks, etc. Right now I’m starting with the trees. I currently have it set up with 2 different objects, the tree roots and the tree itself (I had a posting for instantiating the tree object) the idea being that once the tree is destroyed the roots object has a timer that counts down the respawns a new tree object. I’m wondering if its a better idea to just disable the tree and enable it again to make a “new” tree.
This is the code on the tree
public int numberLogs = 3;
void Update ()
{
if (numberLogs == 0)
{
Destroy (gameObject);
}
}
and on the roots:
void Update ()
{
if (transform.childCount == 0)
{
tree = Instantiate(tree);
tree.transform.parent = this.transform;
tree.transform.localPosition = Vector3.zero;
}
}
So I could theoretically just remove the code on the roots and set the code on the tree to make it inactive rather than destroyed
I’m trying to change things up and instead of destroying the tree gameobject I am just setting it inactive. This way I don’t have to deal with deleting and respawning objects constantly when I don’t need to. Now I’m faced with new issues.
If I set the tree to be inactive, I can’t set a timer on that same script, so it will never respawn.
If I set just the mesh to be inactive I can still use the object because the collision box is still there.
If I set the collision box to inactive then the player can walk in the area where the tree was, making it very dificult if a tree respawns on a player.
Not sure where to go from here so I’ll keep poking around
Using object pooling is a better idea than destroying and instantiating (cleaner code/better performance).
Also for your instantiate code, just use Instantiate(tree) rather than tree = Instantiate(tree). This way it’s creating something new not creating something and setting your prefab reference to it.