As DMGregory noted, a Canvas Group is an easy way to control interactivity for a group of UI controls. Just assign the Canvas Group to the parent containing your UI controls, and update the interactable
property:
canvasGroup.interactable = false;
As for user interaction with non-UI GameObjects, there are several approaches depending on how you process input:
Update()
does not run if the MonoBehaviour is disabled. For example:
public class ClickableGameObject : MonoBehaviour {
void Update() {
if (Input.GetMouseButtonDown(0)) {
//handle click here
}
}
}
clickableGO.enabled = false; //disables the Update() function
- For other functions like
OnMouseDown()
or OnPointerClick()
, you'll need a flag you can check to see if the input should be disabled. There are several ways to do this. Here are a few examples:
//This solution is clean but may require you to call `Interactable = true;` or
//`Interactable = false;` on many objects depending on your game structure.
public class ClickableGameObject : MonoBehaviour {
[SerializeField] private bool interactable = true;
public bool Interactable { get => interactable; set => interactable = value; }
void OnMouseDown() {
if (!interactable) return;
//handle click here
}
}
//this solution uses a global static variable, which is generally bad practice,
//but can save a lot of effort in this case:
public static class UserInput {
public static bool InputEnabled {get; set;} = true;
}
public class ClickableGameObject : MonoBehaviour {
void OnMouseDown() {
if (!UserInput.InputEnabled) return;
//handle click here
}
}
//this solution is a compromise between the above two solutions
public class UserInputSettings {
public bool InputEnabled {get; set;} = true;
}
public class ClickableGameObject : MonoBehaviour {
public UserInputSettings InputSettings { get; set; }
void OnMouseDown() {
if (!InputSettings.InputEnabled) return;
//handle click here
}
}
//create the settings instance before instantiating your GameObjects
UserInputSettings settings = new UserInputSettings();
//assign the settings to your GameObjects immediately after instantiating them
ClickableGameObject clickableGO1 = Instantiate(clickableGOPrefab);
clickableGO1.InputSettings = settings;
ClickableGameObject clickableGO2 = Instantiate(clickableGOPrefab);
clickableGO2.InputSettings = settings;
//affects all GameObjects we've assigned the settings to
settings.InputEnabled = false;