0
votes

I'm making a game with multiple scenes transitions in Unity 2018.1.6 with C#, however I wanted to only have 1 instance of a main camera, a scene controller and perhaps a sound manager at a time during the active scene. I've made it so that the very first scene of the game contains these elements (MainCamera, SceneManager) but not within any other scenes.

I have these elements currently tagged with a do not destroy on load script, and upon scene changes these gameObjects would carry forward in to the next scene.

I wanted to build another failsafe checker for these elements with the logic:

  1. If there is none of these in the scene, create/instantiate one,

  2. If there are more than one, delete the extra.

(This would apply for both Camera and SceneManager)

I'm wondering what is the best approach to do this?

Thanks for your help!

1

1 Answers

0
votes

There are so many different approaches to this, and various opinions on what is right and what isn't.

A simple brute force approach would be for each scene's root script to automatically create your root object (which in turn is responsible for creating your other "essential" game-objects) if it doesn't exist.

Another alternative is to use the RuntimeInitializeOnLoadMethodAttribute. Pseudocode:

public class GameRoot : MonoBehaviour
{
    [RuntimeInitializeOnLoadMethod]
    private static void CreateRoot ()
    {
        GameObject go = new GameObject();
        go.AddComponent<GameRoot> ();
    }

    private void Awake ()
    {
        Debug.Log ("Root created. This will then ensure that the necessary essentials are created.");
    }
}

Keep in mind though that this attribute does not guarantee order/time of creation.

If your game scripts depend on any of your "essentials", you'll need to architect a simpler and straightforward approach, where the dependencies are always created first.

I hope this helps. Good luck!