Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

GetComponent() and instantiation?

Discussion in 'Scripting' started by Wasiim, May 23, 2015.

  1. Wasiim

    Wasiim

    Joined:
    May 2, 2015
    Posts:
    228
    Hello its newb guy, so i am assuming GetComponent() and doing some thing like Bigbro tinybro=new Bigbro();
    both return an instance but what is the diff and when can you use them?
     
    Last edited: May 23, 2015
  2. proandrius

    proandrius

    Unity Technologies

    Joined:
    Dec 4, 2012
    Posts:
    544
    These are two both totally different things.

    GetComponent - Returns a Component that is on the object / instance.
    Bigbro tinybro=new Bigbro(); - Creates new object instance.
     
  3. Wasiim

    Wasiim

    Joined:
    May 2, 2015
    Posts:
    228
    ok so one gets it the other creates sooo.... diff?
     
  4. Aaron_T

    Aaron_T

    Joined:
    Sep 30, 2014
    Posts:
    123
    There is a difference between objects and components. Objects are individual entities, components are things that are attached to objects in your scene.

    In your example, tinybro is a Bigbro object. You can't use GetComponent on any other object to get tinybro, because it exists independently.
    But, if you need to find an object's rigidbody or a script that is attached to it, use GetComponent.
     
    Last edited: May 23, 2015
  5. Wasiim

    Wasiim

    Joined:
    May 2, 2015
    Posts:
    228
    Can you instantiate classes even though a class is monobehaviour wont that prove easier?
     
  6. Aaron_T

    Aaron_T

    Joined:
    Sep 30, 2014
    Posts:
    123
    I don't quite understand your question, but you use will need to use GetComponent any time that you need a particular object's attached component or script.

    For example, with a Health Script that tracks how much health an object has, you might do something like this in the script of a projectile weapon.

    Code (csharp):
    1.  
    2. void OnTriggerEnter(Collider other){
    3.   HealthScript otherHS = other.GetComponent<HealthScript>(); //Get the other object's HealthScript
    4.   otherHS.TakeDamage(); //TakeDamage() is an example of a public function in HealthScript
    5. }
    6.  
    In my example, a HealthScript object is instantiated, and it references the HealthScript component of the object with which it collided.
    Note, you wouldn't even need to make a HealthScript object in this case, as you could just put: other.GetComponent<HealthScript>().TakeDamage();
     
    Wasiim likes this.
  7. Wasiim

    Wasiim

    Joined:
    May 2, 2015
    Posts:
    228
    ok