Unexpected behaviour with GetComponent on Inherited classes

Zaddo

Active member
This is a Unity gotcha and nothing to do specifically with Opsive. But this will potentially impact anyone subclassing Opsive classes.

I created a derived class PunCharacterNew, inheriting from the base Opsive class PunCharacter for the purpose of overriding one of the base methods. The existing Opsive code found the gameobject component for this class by doing a GetComponent<INetworkCharacter>, which PunCharacter implemented. After I replaced PunCharacter with PunCharacterNew on my gameobject, the GetComponent<INetworkCharacter> returned a reference to PunCharacter not PunCharacterNew. I spent hours tying to work out why it did this.

It turns out that GetComponent<Interface> and consequently GetCachedComponent<Interface>, will return the class that directly implements the interface. i.e. Because PunCharacterNew did not directly implement interface INetworkCharacter, it was overlooked by the GetComponent call and the underlying base class was instead returned.

However If I implement the new class as follows:

C#:
    public class PunCharacterNew : PunCharacter, INetworkCharacter

Then calling gameObject.GetCompoent<INetworkCharacter>() , will get a reference to the PunCharacterNew component on the gameobject.

I am just posting this here to possibly save someone else hours of debugging trying to figure this out. The lesson for me is to add all implemented interfaces/classes onto the top level class declaration.

This behaviour might be by design. But it is not obvious and was unexpected.

I am using 2020.1.7f1. I am not sure if this is the same with other versions.
 
Last edited:
Top