Toggle Button: hope it toggle once but it toggle many times

I want to use a Button to achieve a GUI Window toggle. When you press down the “k” Button, it will Toggle the show window. The problem is that when I use the function GetButtonDown(“XXX”), it was called many times in once press rather than once , so it lose the toggle function . Here is the script so far, but I do not know how to fix it.

public class PlayerInput : MonoBehaviour

void Update () {
	
		if (Input.GetButtonDown ("Toggle Inventory")) { 
			Messenger.Broadcast ("ToggleInventory");
		}
}


public class MyGUI : MonoBehaviour

private void OnEnable(){

		Messenger.AddListener ("ToggleInventory", ToggleInventoryWindow);
		
}

public void ToggleInventoryWindow(){

		// it wait fixed
		_displayInventoryWindow = !_displayInventoryWindow ;

}

Hi @bla_whi,

From what I read here Messengers are slow if you make use of them heavily.

I recommend you to use a PropertyChangedEventHandler. An example would be:

public class InventoryManager : MonoBehaviour, INotifyPropertyChanged
{
	public event PropertyChangedEventHandler PropertyChanged;

	private bool _isInventoryOpened = false;
	public bool InventoryOpened
	{
		get { return _isInventoryOpened; }
		set { _isInventoryOpened = value; OnPropertyChanged("InventoryOpened"); }
	}

	private void OnPropertyChanged(string name)
	{
		PropertyChangedEventHandler handler = PropertyChanged;
		if (handler != null)
		{
			handler(this, new PropertyChangedEventArgs(name));
		}
	}

	Update () {
	{
		if (Input.GetButtonDown ("Toggle Inventory")) {
			InventoryOpened= !_isInventoryOpened;
		}
	}
}

Then, in your MyGUI class you add the following:

public class MyGUI : MonoBehaviour
{
	// you need a reference to the inventory manager.
	// In your hierarchy just drag the game object with your MyGUI into that field :)
	public InventoryManager inventoryManager; 

	private bool _displayInventoryWindow = false;
	
	public void Awake()
	{
		if (inventoryManager != null)
			inventoryManager.PropertyChanged += ToggleInventoryWindow;
	}

	public void OnDestroy()
	{
		if (inventoryManager != null)
			inventoryManager.PropertyChanged -= ToggleInventoryWindow;
	}
	
	public void ToggleInventoryWindow(object sender, PropertyChangedEventArgs e)
	{
		if (e.PropertyName.Equals("InventoryOpened"))
		{
			_displayInventoryWindow = !_displayInventoryWindow;
		}
	}
}

Hope this helps. Good luck with your game!
AT

Thanks your help sincerely ,I will try it. :slight_smile: