How to Disable an Interface

Hello guys, I was wondering if there’s a way to disable a script that implements to an Interface. So, I have an IController interface and inside the CharacterManager script, I want all scripts that implements IController to stop taking inputs, so basically disabling it. I can try creating a conditional statement in each scripts but I don’t want to since it gets redundant later on.

public interface IController{
	public void Input();
}

public class CharacterArm: Mono behavior, IController{
	public void Input() {} 
} 

public class CharacterWeapon: MonoBehavior, IController{
	public void Input() {} 
} 

public class CharacterManager: MonoBehavior{
	private IController[] inputs;

	private void Start() {
		inputs = transform.GetComponentsInChildren<IController>();
    } 

	private void Update() {
		if(Character.Instance.getHealth){
			for(int i = 0; i < inputs.Length; i++) {
				//error
				inputs*.enabled = false;*
  •  	}* 
    
  •  }* 
    

}
}
Sorry for this question guys, this is my first time and I’m only using my phone. Sorry for the inconvenience! But thank you if you have an answer to this…

You have two options:

  • You can either require your interface to have an enabled property. That way any class derived from MonoBehaviour would comply.
  • Or once you have the reference to your interface, check and convert the reference to MonoBehaviour and call enabled on it.

An interface is just a contract for methods. Any kind of class could implement an interface, not just Unity Components. So an reference to an instance of an interface type is not required to be a MonoBehaviour. Of course GetComponent can only return components, however the C# compiler does not know this. In the end he has an array that contains references to class instances which implement this interface.

// first solution
public interface IController
{
    public void Input();
    public bool enabled {get; set;}
} 

In the second case you can do

for(int i = 0; i < inputs.Length; i++)
{
    if (inputs *is MonoBehaviour mono)*

mono.enabled = false;
}
or the classical way:
for(int i = 0; i < inputs.Length; i++)
{
MonoBehaviour mono = inputs as MonoBehaviour;
if (mono != null)
mono.enabled = false;
}
This should fix your issues.

You mean user inputs? Like keyboard + mouse? If so, the way I handle user input is having it all in a script inside functions, and one main function to call the others. If I want to disable input, I just break out of the function early on so the inputs read wont make a difference in the code. The most efficient way would be to find a way to put a conditional statement in IController, create a function that handles the inputs, and only proceed if the condition in IController is met. Does that help you? If not, feel free to talk to me