Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Instantiate an object

Discussion in 'Editor & General Support' started by unity_E0-SHClrUHuAng, Jul 14, 2020.

  1. unity_E0-SHClrUHuAng

    unity_E0-SHClrUHuAng

    Joined:
    May 29, 2020
    Posts:
    2
    Hi everyone,

    I'm doing a Unity 2D course and I was asked to instantiate an object (a Defender for a Plants vs Zombies game), and my solution was:
    Code (CSharp):
    1. Instantiate (defender, transform.position, Quaternion.identity);
    what my instructor used instead was:
    Code (CSharp):
    1. GameObject newDefender = Instantiate(defender, transform.position, Quaternion.identity) as GameObject;
    what is exactly the difference between the two codes?
     
  2. fffMalzbier

    fffMalzbier

    Joined:
    Jun 14, 2011
    Posts:
    3,276
    Your first code does just instantiates the object.
    The second code peace does in addition save the instantiated gameobject in a variable called newDefender.
     
    unity_E0-SHClrUHuAng likes this.
  3. unity_E0-SHClrUHuAng

    unity_E0-SHClrUHuAng

    Joined:
    May 29, 2020
    Posts:
    2
    I see! it actually makes very much sense! Thank you!
     
  4. dgoyette

    dgoyette

    Joined:
    Jul 1, 2016
    Posts:
    4,120
    And presumably, your instructor should be making use of the newDefender somewhere later in that block of code, otherwise there's no reason to have stored the reference to it. Usually the compiler will give you a warning if you store a value in a variable but you never make use of that value. Perhaps a bit later in your instructor's code they're doing something with newDefender?