Difference between Destroy and Destroy immediate (In this case).

Hey I am trying to make a tic tac toe game in unity, so i am instantiating my X and O’s, so when I need to start a new game, I need to clear out all the previously instantiated X and O’s. So, I am using the following method to do so :-

public void NewGame()
    {
        for (int i = 0; i < 9; i++)
        {
            p1WinCond *= 0;*

p2WinCond = 0;
pos*.gameObject.SetActive(true);*
}

for (; buttonPresses != 0; buttonPresses–) //to count the no. of X and O’s
{
DestroyImmediate(GameObject.Find(“O(Clone)”));
DestroyImmediate(GameObject.Find(“X(Clone)”));
}

this.transform.GetChild(4).gameObject.SetActive(false);
GameOver = false;
player1Wins.SetActive(true);
player2Wins.SetActive(true);
}
Ignore the rest of the code, so, when I use Destroy func. only the first X and the first O are being destroyed, the rest remain as it is, despite the loop running its full course. But, when I use Destroy immediate it works as desired all of them are deleted.
wanted to know why is it so?
Also, any alternative approach to the problem is appreciated too.Thank You.

Destroy() just marks an object to be neatly destroyed at the end of the frame. DestroyImmediate as the name suggests, destroys the object right then and there with some overhead.


In your loop when you Find the objects, it only returns the first ones it finds. So when you use Destroy(), you just keep marking the first ones for destroy and never get to the rest. While using DestroyImmediate() it destroys them in that loop, so that in the next loop the Find sees the next objects.


It is better to use Destory() only in your game. If the O or X objects have a script on them you can use FindObjectsOfType to get all of them at once in an array, then you can use Destory() on them. You can also use tags. Put a tag on the prefab, then you can use FindGameObjectsWithTag

You have your answer already,but as an aside: Generally, if you can you might want to avoid using Destroy () too much. In a small tic tac toe game, k. No biggy.Not a lot of objects. If you start using destroy when every one of thousands of bullets as they fly across your screen, it becomes really bad really fast.

it’s better practice to move the object you want to destroy off screen, into a ‘pool’ and hide it. Then when you need one of them again, you just bring that back instead of instantiating a new one. Again, in a small little game of tic tac toe, no big deal if you do it the destroy way. But as your projects get bigger, this would be a better practice.