Many gameobjects in my game has a OnMouseDown() event of its own. When my player is doing a certain action, I don’t want the gamer to accidentally activate any of these mouse events. I could just use a boolean variable to track it down, but that would acquire me to change too many scripts in my game.
I’m wondering if there’s a way to disable the mouse button for a while in script?
Sure, use a boolean to control the flow, or disable the collision component or completely disable the gameobject.
The next option is to change the way you’re implementing controls/interaction in your game… revisit the logic.
You already pretty much answered your own question in your original post. If you want to disable something periodically… you will have to evaluate something that returns true or false.
Two ways come to mind if you want to disable Input globally. There is no Unity’s own method, you’ll have to implement your own solution. First is that you create a wrapper for Input
class which has a flag it checks before processing the input, and you call this Input class’s method instead of directly calling Unity’s. This way you’ll have more control is maybe in some situation future you don’t want to turn off all input. Second is create a persistent singleton with a flag inputAllowed
, add an instance, and in every OnMouseDown
, OnMouseUp
etc. check that it’s set to true before continuing. Below is template class you could include in your project, it just simplified creating singletons. I would also recommend reading the link above.
using UnityEngine;
/// <summary>
/// Persistent singleton.
/// </summary>
public class PersistentSingleton<T> : MonoBehaviour where T : Component
{
private static T _instance;
/// <summary>
/// Singleton design pattern
/// </summary>
/// <value>The instance.</value>
public static T Instance
{
get
{
if (_instance == null)
{
_instance = FindObjectOfType<T> ();
if (_instance == null)
{
GameObject obj = new GameObject ();
obj.hideFlags = HideFlags.HideAndDontSave;
_instance = obj.AddComponent<T> ();
}
}
return _instance;
}
}
/// <summary>
/// On awake, we check if there's already a copy of the object in the scene. If there's one, we destroy it.
/// </summary>
public virtual void Awake ()
{
DontDestroyOnLoad (this.gameObject);
if (_instance == null)
{
_instance = this as T;
}
else
{
Destroy (gameObject);
}
}
}
Now to create a singleton class you simply have to do
public class InputControllerSingleton: PersistentSingleton<MonoBehaviour> {
public bool inputAllowed{ get; set; }
IEnumerator turnOffInputFor(float seconds){…}
}
//Simple check when you receive input.
if (!InputControllerSingleton.instance.inputAllowed)
return;
There is no way to turn off input with a single line of code, you’ll have to check a condition in every input method. Use a wrapper if you want to extend the Unity’s Input
class, otherwise singleton should do just fine.