Search Unity

  1. Looking for a job or to hire someone for a project? Check out the re-opened job forums.
    Dismiss Notice
  2. The Burst compiler has its own forum section now.
    Dismiss Notice
  3. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

Writing a GameManager Tutorial

Discussion in 'Scripting' started by Hawkadium, Jul 20, 2020.

  1. Hawkadium


    Oct 7, 2014
    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

    Code (CSharp):
    1.     private void Start()
    2.     {
    3.         DontDestroyOnLoad(gameObject);
    5.         _instancedSystemPrefabs = new List<GameObject>();
    6.         _loadOperations = new List<AsyncOperation>();
    8.         InstantiateSystemPrefabs();
    10.         LoadLevel("Main");
    11.     }
    13.     void InstantiateSystemPrefabs()
    14.     {
    15.         GameObject prefabInstance;
    16.         for (int i = 0; i < SystemPrefabs.Length; ++i)
    17.         {
    18.             prefabInstance = Instantiate(SystemPrefabs[i]);
    19.             _instancedSystemPrefabs.Add(prefabInstance);
    20.         }
    21.     }
  2. PraetorBlue


    Dec 13, 2012
    When you call Instantiate it creates a new GameObject, you got that part right. In your case you're doing this:
    Code (CSharp):
    1. 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:
    Code (CSharp):
    1. prefabInstance = Instantiate(SystemPrefabs[i]);
    That stores a reference to the newly created GameObject from Instantiate in the variable
    . Now you can do other things with this new instance.

    For example:
    Code (CSharp):
    1. _instancedSystemPrefabs.Add(prefabInstance);
    This puts the newly instantiated GameObject into the list called

    That's all there is to it!
    Hawkadium likes this.
  3. Hawkadium


    Oct 7, 2014
    Oh that makes a lot of sense. Thank you for the reply.