I’m still trying to get my mind around interfaces and their uses. I have an EventManager which handles events such as this, sent from a UFOController script when the UFO is hit by a player weapon:
EventManager.Instance.UFOKilledByPlayer(this);
This is picked up by EventManager, which has this among other things:
public Action<UFOController> OnUFOKilledByPlayer;
public void UFOKilledByPlayer(UFOController ufo) { if (OnUFOKilledByPlayer != null) OnUFOKilledByPlayer(ufo); }
I have a UIManager component which subscribes to that event and displays a small score value where the UFO was hit, like this:
public void ShowPointsAtScreenPosition(UFOController ufo)
{
Text t = Instantiate(textRoaming);
t.transform.SetParent(canvas.transform, false);
t.transform.position = Camera.main.WorldToScreenPoint(ufo.gameObject.transform.position);
t.text = ufo.pointValue.ToString();
Destroy(t, 1.0f);
}
This works fine. However, it only works for the UFOController class. So I tried to generalize so I could apply to other objects which are not UFOs, by defining a basic “IKillable” interface and adding it to the UFOController class (in the class declaration line, next to MonoBehaviour):
public interface IKillable {
void Kill();
}
If I now redefine the event in EventManager:
public Action<IKillable> OnSomethingKilledByPlayer;
And do the same everywhere along the chain of events, I get to this:
public void ShowPointsAtWorldPosition(IKillable k)
{
// blah
}
But I can’t find any way of finding the object that the variable k came from. I read somewhere that I should cast it but it doesn’t seem to work, even if I cast it to MonoBehaviour.
As a side note, I can put the “ShowPoints” method as a separate, dedicated component on the gameobjects I’d like to use it, so that they display their point value themselves before being destroyed by Unity, or (maybe better) on the explosion gameobject itself that is instantiated when destroyed (a particle effect and an audio clip). This would seem to conform to the Unity principle of “one component per behaviour”. But then I’m totally coupling the UI to the game logic, am I not?
Thanks for your help.