Friday, February 5, 2016

Pseudo Polymorphism in Inspector

This is the closest I've been able to come in creating polymorphic assignment with game objects in the inspector.

The interface or abstract-base-class would be defined as below.  Note the keyword "virtual" must be used here.

public class IEventTrigger : MonoBehaviour
{
   public virtual void OnEvent()
   {}
}

Next the derived class inherits from this pseudo-interface.  Note in this case, the implementation must be overridden using the "override" keyword.

public class TriggerPrint : IEventTrigger
{
   public override void OnEvent()
   {
      Debug.Log("Event Logged");
   }
}

An example now of a class that takes a game-object that has the TriggerPrint script component.  When eventHandler.OnEvent() is called, it will call the TriggerPrint.OnEvent().

public class InputManager : MonoBehaviour 
{
   [SerializeField]
   private IEventTrigger eventHandler;

   // Use this for initialization
   void Start ()
   {
      eventHandler.OnEvent();
   }
}

No comments:

Post a Comment