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

How to have GetComponent<> get the base class and not a derived class?

Discussion in 'Scripting' started by douglasg14b, Jan 25, 2015.

  1. douglasg14b

    douglasg14b

    Joined:
    Oct 2, 2014
    Posts:
    34
    Lets Say I have this:

    Class A (Extends MonoBehavior)
    Class B (Extends A)

    Both A & B are attached to my object as components.

    I need a script to access all public members of class A.

    When I try and use:
    Code (CSharp):
    1. public A classA;
    2.  
    3. OnStart()
    4. {
    5.     classA = GetComponent<A>();
    6. }
    The inspector shows None (A) like it should before the game runs. When I run the Game it will not show GameObject (B) instead of the expected GameObject (A).

    When the game runs it gets B instead of A.

    How do I have GetComponent<> get the base class and not a derived class?

    Edit: I have done a google search on this and read the unity answers and forum posts others have made. I am not quite understanding to solutions that where given.
     
  2. cmcpasserby

    cmcpasserby

    Joined:
    Jul 18, 2014
    Posts:
    315
    Just use GetComponent on the game Object using the class name of the base class of the component you want. If you do so it will downcast by its self.

    Also if you already got reference to the child class you can simply cast to the base class.
     
    Kiwasi likes this.
  3. MakeCodeNow

    MakeCodeNow

    Joined:
    Feb 14, 2014
    Posts:
    1,246
    I think the problem is that you're kind of abusing inheritance. If B derives from A, then it can do everything an A can do. If you have a B on your object, you shouldn't also need an A.

    Another way you can think of components is that they add abilities to your game object. Inheritance is designed to allow the child to have all of the abilities of the parent, plus more. In that sense, there is no point in adding the same abilities twice, which is what happens if you add both A and B.
     
    ArthurZBaney likes this.