Daarwin
Daarwin

Reputation: 3014

Cant cast monobehaviour base class

I have a baseclass that inherits from Monobehaviour. How do i cast my monobehaviour to the base class when finding it in the hierarchy?

GameManager : MonoBehaviour {

    public MonoBaseClass MyThing;

    void Awake() {
        MyThing = GameObject.Find("Child") as MonoBaseClass;
    }
}

MonoBaseClass : MonoBehaviour  {

    public void BaseClassMethod() {}

}

Upvotes: 0

Views: 552

Answers (3)

derHugo
derHugo

Reputation: 90620

Problem with both Find and FindObjectOfType is: They are quite slow and you will get the first hit from the entire scene.

If the Component you are looking for is on a Gameobject which is a child of the current GameObject (which seems the case) than you can just use:

MyThing = GetComponentInChildren<MonoBaseClass>();

https://docs.unity3d.com/ScriptReference/Component.GetComponentInChildren.html

Of course this will anyway still only get the first hit. For more use an array and GetComponentsInChildren<T>()

Upvotes: 1

R1PFake
R1PFake

Reputation: 420

GameObject.Find returns a GameObject, a MonoBehaviour is a component of a GameObject. That's why you can't cast the GameObject to the MonoBaseClass.

Instead you have to get a reference of the GameObject and then get the Component:

GameObject childGameObject = GameObject.Find("Child");
MyThing = childGameObject.GetComponent<MonoBaseClass>();

Upvotes: 2

Galandil
Galandil

Reputation: 4249

You need to use FindObjectOfType<MonoBaseClass>(), i.e.:

void Awake() {
    MyThing = FindObjectOfType<MonoBaseClass>();
}

Upvotes: 1

Related Questions