Writing a GameManager Tutorial

Hello, I am following a Unity Game Dev Course. My code works but I am a bit confused about where the GameObject is actually told to Instantiate. Is it from using “Instantiate” with a capital “i” and this somehow tells Unity to just do this automatically? If that is true, it doesn’t really make sense why we are setting it to a “prefabInstance” variable in the same line. Can someone explain this? Thanks

    private void Start()
    {
        DontDestroyOnLoad(gameObject);

        _instancedSystemPrefabs = new List<GameObject>();
        _loadOperations = new List<AsyncOperation>();

        InstantiateSystemPrefabs();

        LoadLevel("Main");
    }

    void InstantiateSystemPrefabs()
    {
        GameObject prefabInstance;
        for (int i = 0; i < SystemPrefabs.Length; ++i)
        {
            prefabInstance = Instantiate(SystemPrefabs[i]);
            _instancedSystemPrefabs.Add(prefabInstance);
        }
    }

When you call Instantiate it creates a new GameObject, you got that part right. In your case you’re doing this:

Instantiate(SystemPrefabs[i]);

This code just means “Create a new object that’s a clone of the prefab at index i of the SystemPrefabs array”. It also places that new object in the current game scene. So you will get a new GameObject as a result that’s a clone of one of the objects from that array. (in fact the for loop guarantees you will be creating one clone of each object in the array).

Sometimes when you create a new object, you want to do something with that object. That’s where the variable assignment comes into play. So you have this:

prefabInstance = Instantiate(SystemPrefabs[i]);

That stores a reference to the newly created GameObject from Instantiate in the variable prefabInstance. Now you can do other things with this new instance.

For example:

_instancedSystemPrefabs.Add(prefabInstance);

This puts the newly instantiated GameObject into the list called _instancedSystemPrefabs

That’s all there is to it!

1 Like

Oh that makes a lot of sense. Thank you for the reply.