using System; using UnityEngine; using Framework.Services; namespace Framework.State { /// Can be implemented by a component to make it user-controllable public class PlayerControllable : ScriptComponent, IControllable { /// Triggered when control of the game object is being taken public event Action ControlTaken; /// Triggered when control of the game object has been released public event Action ControlReleased; /// Initialized a new player controllable public PlayerControllable() { this.controllingPlayerIndex = -1; } /// Called when the player takes control of the controllable /// Index of the player that has taken control public void OnTakeControl(int playerIndex) { if(this.controllingPlayerIndex != -1) { Debug.LogError( "Player " + playerIndex.ToString() + " tried to take control of '" + gameObject.name + "' but player " + this.controllingPlayerIndex.ToString() + "already has control!" ); return; } this.controllingPlayerIndex = playerIndex; if(ControlTaken != null) { ControlTaken(playerIndex); } Debug.Log("Player " + playerIndex.ToString() + " is now in control of " + gameObject.name); } /// Called when the player releases control o the controllable /// Index of the player that has released control public void OnReleaseControl(int playerIndex) { if(this.controllingPlayerIndex == -1) { return; // Double-frees are a sign of shitty coding but not an error } if(this.controllingPlayerIndex != playerIndex) { Debug.LogError( "Player " + playerIndex.ToString() + " tried to yield control of '" + gameObject.name + "' but it is being controlled by player " + this.controllingPlayerIndex.ToString() ); return; } this.controllingPlayerIndex = -1; if(ControlReleased != null) { ControlReleased(playerIndex); } Debug.Log("Player " + playerIndex.ToString() + " released control of " + gameObject.name); } /// Index of the currently player currently in control, -1 for none public int ControllingPlayerIndex { get { return this.controllingPlayerIndex; } } /// Index of the player currently in control of this controllable private int controllingPlayerIndex; } } // namespace Framework.State