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

Inheritance in scripts

Discussion in 'Scripting' started by Ap0C552, Feb 22, 2015.

  1. Ap0C552

    Ap0C552

    Joined:
    Feb 7, 2015
    Posts:
    43
    I am wondering the implication inheritance has in MonoBehaviors.

    For example.

    When I call GetComponentType<T>(); it will return me the instance of the Type of script on the associated GameObject, correct? I am under the impression you can not have two of the same script on a GameObject

    Scenario

    what is I have..

    Class Base
    Class Child1 : public Base
    Class Child2 : public Base

    Is it possible to have an instance of both a Child1 and a Child2 on my GameObject. What will then happen if I call....

    GetComponentType<Base>();

    ??
     
  2. cmcpasserby

    cmcpasserby

    Joined:
    Jul 18, 2014
    Posts:
    315
    If you call GetComponent on the base you just get a object back that only has the methods and fields owned in the base class.

    Also you can have multiple scripts of the same type on one object t no problem.
     
  3. Ap0C552

    Ap0C552

    Joined:
    Feb 7, 2015
    Posts:
    43
    If you can have mulitple scripts of the same type on an object what will GetCompenent<T> return if there are two scripts of type T on the object???
     
    Last edited: Feb 23, 2015
  4. cmcpasserby

    cmcpasserby

    Joined:
    Jul 18, 2014
    Posts:
    315
    Sorry GetComponents<T>() which returns a array of T
     
  5. Ap0C552

    Ap0C552

    Joined:
    Feb 7, 2015
    Posts:
    43
    yes but what happens if I have multiple T and I call GetComponent<T>. What is the rule for which of the multiple T will be returned?
     
  6. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    GetComponent will return the first one Unity finds. Note that this is not always the first one in the inspector. Its essentially undefined behaviour, so if you want more then one instance of the same component on a single GameObject don't use GetComponent.

    To have multiple components use GetComponents instead.
     
  7. Ap0C552

    Ap0C552

    Joined:
    Feb 7, 2015
    Posts:
    43
    Ahh ok thank you for the response!