using System;
using UnityEngine;
using Framework.Services;
namespace Framework.State {
/// Manages the game object currently being controlled by the player
[ServiceScope(Scope.Scene)]
public class ControlManager : Service, IControlManager {
/// Called when the player switches control to another controllable
public event Action ControlSwitched;
/// Maximum number of players the control manager will deal with
public int MaximumPlayerCount = 4;
/// Called when the component gets loaded into a game object
protected override void Awake() {
base.Awake();
this.frozenMaximumPlayerCount = this.MaximumPlayerCount;
this.activeControllables = new IControllable[this.frozenMaximumPlayerCount];
}
/// Lets a player assume control of the specified controllable
/// Index of the player that will assume control
/// Controllable the player will be controlling
public void AssumeControl(int playerIndex, IControllable controllable) {
if(playerIndex > this.frozenMaximumPlayerCount) {
string controllableName = "controllable";
MonoBehaviour behavior = controllable as MonoBehaviour;
if(behavior != null) {
controllableName = behavior.gameObject.name;
}
Debug.LogError(
"Player " + playerIndex.ToString() + " tried to take control of '" +
controllableName + "' but control manager has been configured to only " +
"support " + this.frozenMaximumPlayerCount.ToString() + " players!"
);
return;
}
IControllable previousControllable = this.activeControllables[playerIndex];
if((previousControllable as Component) != null) {
previousControllable.OnReleaseControl(playerIndex);
}
this.activeControllables[playerIndex] = controllable;
controllable.OnTakeControl(playerIndex);
OnControlSwitched(playerIndex, controllable);
}
/// Gets the controllable currently active for the specified player
///
/// Index of the player whose active controllable will be returned
///
/// The controllable currently active for the specified player
public IControllable GetControllable(int playerIndex) {
if(playerIndex > this.frozenMaximumPlayerCount) {
Debug.LogError(
"Tried to look up controllable for player " + playerIndex.ToString() + ", " +
"but control manager has been configured to only support " +
this.frozenMaximumPlayerCount.ToString() + " players!"
);
return null;
}
if((this.activeControllables[playerIndex] as Component) == null) {
return null;
} else {
return this.activeControllables[playerIndex];
}
}
/// Fires the ControlSwitched event
/// Index of the player that has switched control
/// Controllable that has obtained control
protected void OnControlSwitched(int playerIndex, IControllable controllable) {
if(ControlSwitched != null) {
ControlSwitched(playerIndex, controllable);
}
}
/// Value of when the game started
private int frozenMaximumPlayerCount;
/// Controllables currently being controlled by each player
private IControllable[/*frozenMaximumPlayerCount*/] activeControllables;
}
} // namespace Framework.State