Problem with TryGetComponent, interfaces and inheritance

Hi, the following is happening to me. I have a class that implements an interface.

This is the interface:

public interface IEventInfo
{
        public SEventData EventData { set; get; }
}

And this is the class:

public class EventManager : IEventInfo
{
        public SEventData EventData { set; get; }
}

Then I have another class derived from the above:

public class EntityEventBase : EventManager
{ 
    [Header("Event Data")]
    public SOEventData sOEventData; //ScriptableObject

    public override void Start()
    {
        base.Start();
        eventData = new SEventData(sOEventData); 
        EventData = eventData;
    }
}

And finally I have another “enemy” class derived from the previous one.

public class Enemy : EntityEventBase
{
    public override void Update()
    {
        base.Update();   
        Debug.Log(this + " " + EventData.eventType  + " " + EventData.eventProperty);
    }
}

From the enemy class I can get the “EventData” data without any problem.
But from the Player class I try to read the data and it doesn’t work. Everything has zero value.

Player Class:

public virtual void OnTriggerEnter2D(Collider2D collision)
{
        if (collision.gameObject.TryGetComponent(out IEventInfo iEventInfo))
        {
            Debug.Log(this + " " + collision.gameObject.tag + "  + iEventInfo.EventData.eventType + " -->" + iEventInfo.EventData.eventProperty);
        }
    }

I think the TryGetComponent function is getting the data from the EventManager class instead of the Enemy class.

I am right?
Or am I doing something wrong?
Can I do something to get the data from the Enemy class instead of the EventManager class?

Thank you so much!!

Well, if you have multiple components what implements the interface, you will get the very first one in the TryGetComponent. If you have multiple components of the same type, use https://docs.unity3d.com/ScriptReference/GameObject.GetComponents.html and sort it out which one you want. Or change up your strategy and look for the Enemy type in the TryGetComponent.

1 Like

Thank you so much for your help!!