Why doesn't this simpler logic work?

If I use the logic below I would expect that only one music player object would ever be created but when I return to the “START” screen, yet another music object is created and two are then playing…

            static MusicPlayerScript  coMusicPlayerScript = null;

	if (coMusicPlayerScript == null) {
		print ("music object == null");
		coMusicPlayerScript = this;
		GameObject.DontDestroyOnLoad(gameObject);
	}
	else {
		print ("music object != null");
	}

I realize that this issue has to do with the internal cycle of Unity. However, if I test for a null value in the static variable at the first time the “Start” method is executed and then fill that variable with an object instance this first time through, the static variable should always contain the object instances throughout the game session.

Why does it not forcing me to use the suggested technique with the “Destroy” method?

Thank you…

Why would this script prevent a second object from being created?

Nothing in here creates the object. Since the script isn’t responsible for the creation of the object, it’s doesn’t prevent it either.

What it does do is assign the DonDestroyOnLoad to one of the objects. That means when you go onto the next level and all objects from this level are destroyed, one of them won’t be destroyed.

Thank you, Anthony…

I wasn’t sure exactly what was doing the object creation here. And since I wasn’t using a “new” statement anywhere it should have been obvious to me that I was not creating any such objects but merely defining a container for them.

That being true, if Unity3d is creating the objects in this instance then I can see now where additional objects would be created and tagged onto the object list hierarchy during the running of the game.

Isn’t there a more efficient way to have Unity3d only create a single object or more based on a setting? It seems rather inefficient to have Unity3d keep on creating game objects in this case only to have them destroyed.

1 Like

Yes, and later in this section or the next one, they address that. I think it’s in Laser Defender, because that’s where you finally learn to create objects.

Once you’re directly in control of creating an object, you can put in a condition to decide whether or not to create it.

1 Like