[Suggestion] GameObject.GetInterface<T>

Hello guys. This thread contained some suggestions about Interfaces and GetComponent.

It was all wrong, so I suggest mods to delete the thread. I’m deleting its content to avoid further confusion.

Thanks!

You know the bog standard GetComponent methods and similar already works with interfaces, right?

2 Likes

Uhm, GetComponent does no longer has a generic constraint to Component for years. So you can directly use interface types as generic argument. So your extension methods are kinda pointless and just more expensive.

1 Like

Will do some testing and remove the post if that’s the case, I remember I went this way for a specific reason when I started but can’t recall what it was.

You guys are right. Embarrassing! I did the first test a while a go, and I don’t know what made me go the LinQ route but the next time I took it went on with that assumption.

Sorry!

Well, there’s an issue using GetComponent directly when testing in the editor as when testing in the editor GetComponent will return a fake null object in case the component is not found. Since the return type is an interface type in our case, you can’t do a normal null check as it does not use Unity’s overloaded == operator since the interface type of course is not derived from UnityEngine.Object.

I would highly recommend to use the TryGetComponent method anyways. It avoids those fake null objects inside the editor. The alternative is to do a proper UnityEngine.Object null check if you have a non UnityEngine.Object reference. Which is

if (obj != null && !obj.Equals(null))
{
    // yes, we actually have a component with that interface.
}
1 Like