World hierarchy doesn't finish destroying before starting a new world?

Hi all

This is an awkward one to explain concisely.

Basically, I have a “restart the game” function that looks like this:

function startNewGame(){
	// If there is a game in progress, end it
	var currentGame = gameObject.GetComponent(gameScript);
	Destroy(currentGame);

	// Start a new game
	gameObject.AddComponent(gameScript);
}

gameScript’s Destroy function goes on to Destroy() the world, the players, etc and those in turn Destroy() their own children.

Now, I think what I’m seeing is this: the game hasn’t finished clearing itself up before the new game is started. I’m getting artefacts like players falling through the level on the 2+ time the level is created, because it would seem the first and subsequent games haven’t been destroyed properly.

One thing I have tried is making it so after the first game everything is destroyed but the second level is not created. In the inspector I then trigger the creation of the next level. This is made flawlessly!

I’m really at a loss of what to do now. Is my method of cleaning up the game completely wrong? How can I ensure everything is destroyed before moving on to build the next level?

Any advice is massively appreciated.

Thanks,

Vesuvian

You might want to check out the official script reference page for Destroy(), which I will quote in part:

Actual object destruction is always delayed until after the current Update loop

Like aldonaletto says, you might try just loading (or reloading) a level.

If you really want to do things this way, you could do something that waits one frame, or otherwise makes sure that the object(s) in question have been destroyed.

You might try DestroyImmediate(), but the script reference doesn’t recommend it.