Unfortunately, when said collider DOESN’T have this component, i receive tons of this warning:
“GetComponent requires that the requested component ‘MyClass’ is inherited or implemented by ‘ColliderName’.”
And I DON’T LIKE TONS OF WARNINGS :((((
Can anybody tell me what should be the “good practice” code to check if a game object has or hasn’t a component, without triggering this warning?
I think I nailed the problem… MyClass is not actually a class, but an Interface, and so the engine doesn’t know if the object derives or not from MonoBehaviour.
If I try to switch the class, it works fine, but if I check for an interface, I get the warning. Damn.
Make the class inherit the interface.
Interfaces shouldn’t really need to be used in Unity to create GameObject behaviour, as that’s what the Component system is for. The only thing I use interfaces is for the back-end code, such as connecting to servers/databases etc.
Well what I did is changing the interface into an abstract class inheriting MonoBehaviour, and it was solved.
I firmly disagree on not using interfaces in behaviours as a principle, but that’s a matter of opinion
Please notice that I consider the current solution a “workaround”, not a real solution. If design says there goes an interface, then there goes an interface. Putting a class is suboptimal.
MyClass MyObject;
MyObject=null; // just in case you are reusing it and want it cleared
try{
MyObject = (MyClass) ColliderUnderCheck.gameObject.GetComponentInChildren(typeof(MyClass));
}catch(e){}
if(MyObject != null)
StuffHappens();
I think that for normal programming applications, such as in business and data areas, it would be silly not to use interfaces. However, the component model that unity uses is essentially using “interfaces”. It’s the whole idea of composition.
I see it as this, in Unity, GameObjects are your classes, but your Components/MonoBehaviours are the interfaces, just you specify the actual logic of those “interfaces” in the component itself, instead of in the “class” (i.e. the GameObject).
Yeah maybe that’s me, I’m not yet used to unity phylosophy about components, objects, stuff… and i’m just pissed off because my normal approach didn’t work. It came so natural to me to use an interface that I even forgot to mention it in the first post.
Anyway, the workaround of the abstract class works, so it’s good until I need more.
Thanks, the problem is exactly the same.
Unfortunately the thread is inconclusive. I’ll try the trick of storing the type in a variable, then we’ll see.