0
\$\begingroup\$

I have a few GameObjects that implement a common Interface: IsTree. I need to call the function doTreeThing() on each of those IsTrees after getting a reference to each of them via FindGameObjectsWithTag("tree").

This line complains that it cannot implicitly convert from GameObject[] to IsTree[]

IsTree[] trees = GameObject.FindGameObjectsWithTag("tree");

So then I tried to leave the GameObject[] an iterate over it to convert each individual object inside to an IsTree.

GameObject[] trees = GameObject.FindGameObjectsWithTag("tree");
        foreach (GameObject tree in trees) {
            IsTree isTree = (IsTree)tree;
            isTree.doTreeThing();
        }

But this complains that it also cannot convert GameObject to IsTree.

Then I got a little desperate and tried to make my IsTree into a GameObject.

public class IsTree : GameObject {
    public System.DateTime getAge(){
        return null;
    }
}

GameObject is a sealed type. (I don't really know what that means besides that this does not work)

So how do I get this array of GameObjects into an array of SomeInterface?

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Did you consider FindObjectsOfType<Tree> instead? \$\endgroup\$
    – DMGregory
    Feb 10, 2020 at 8:33

1 Answer 1

1
\$\begingroup\$

GameObjects are not their components. They are containers for their components. So once you have the GameObject, you have to get the component from it, rather than just assume it is it.

GameObject[] trees = GameObject.FindGameObjectsWithTag("tree");
foreach (GameObject tree in trees) {
    IsTree isTree = tree.GetComponent<IsTree>();
    isTree.doTreeThing();
}

DMGregory’s suggestion should also work:

IsTree[] trees = GameObject.FindGameObjectsOfType<IsTree>();
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .