Search Unity

How does 'Instantiate' convert easily between GameObject and Component?

Discussion in 'Scripting' started by Shack_Man, Dec 18, 2020.

  1. Shack_Man

    Shack_Man

    Joined:
    Jun 7, 2017
    Posts:
    282
    Code (CSharp):
    1. public class Missile : MonoBehaviour
    2. {
    3.     public int timeoutDestructor;
    4.  
    5.     // ...other code...
    6. }
    7.  
    8.  
    9. public class ExampleClass : MonoBehaviour
    10. {
    11.     // Instantiate a Prefab with an attached Missile script
    12.     public Missile projectile;
    13.  
    14.     void Update()
    15.     {
    16.    
    17.         if (Input.GetButtonDown("Fire1"))
    18.         {
    19.             // Instantiate the projectile at the position and rotation of this transform
    20.             Missile clone = Instantiate(projectile, transform.position, transform.rotation);
    21.  
    22.  
    23.         }
    24.     }
    25. }

    This is from the docs. I always took it for granted, but got curious how this method knows how to return a specific component, but also an object. I can see that it uses generics ( public static T Instantiate<T>(T original) where T : Object; ), but how does a component fall under object? When I try to write this myself, I get an error.

    Anyhow, just thought I'd ask, maybe I and others can learn something useful here?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    20,215
    Capitalization matters:
    object
    is not
    Object
    ... in this case
    Object
    means
    UnityEngine.Object
    and the reason it works is:

    Screen Shot 2020-12-18 at 5.03.13 AM.png
     
    PraetorBlue, Vryken and Shack_Man like this.
unityunity