How can I check if more than one GameObject with same Name exists

I have 3 Levels in my game and each level uses the same Game Logic. I create a Game Logic Object in the first Level and use DontDestroyOnLoad so it transfers in the next level with the same health etc.

My problem is that if you die in the first Level and the scene reloads it will have two GameLogic Objects (One that didn’t destroyOnLoad and one that is getting created by loading the scene).

I know how to find a GameObject and check if one exists but how can I check if there is more than one? And how can I delete one of them?

Thank you for any suggestions or solutions!

You can add a simple script into every scene that handles creating the Game Logic Object but only once.

For example:

public class GameStartController : MonoBehaviour
{
    // state of static fields persist even if scene is reloaded
    public static bool gameJustStarted = true;

    private void Awake()
    {
        if(!gameJustStarted)
        {
            return;
        }
        gameJustStarted = false;

        LoadGameLogic();
    }
    ...

This would have the additional benefit that you could start the game from any scene, which would make play-testing easier.

2 Likes

Very helpful, thank you very much!

1 Like

And if you want to get multiple objects by name fast for whatever purpose, use tags instead of names.

1 Like