Search Unity

Writing a GameManager Tutorial

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

  1. TeKniKo64

    TeKniKo64

    Joined:
    Oct 7, 2014
    Posts:
    30
    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);
    4.  
    5.         _instancedSystemPrefabs = new List<GameObject>();
    6.         _loadOperations = new List<AsyncOperation>();
    7.  
    8.         InstantiateSystemPrefabs();
    9.  
    10.         LoadLevel("Main");
    11.     }
    12.  
    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

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,909
    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
    prefabInstance
    . 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
    _instancedSystemPrefabs


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

    TeKniKo64

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