Search code examples
c#unity-game-engineinputunity-ui

Unity wrong instance of class is being called on click. Creating my own input manager.


I am making my own InputManager to remap keys during the game.

The problem is that I have assigned class to each of shortcut's parent and when the button is pressed on the debugger I can see data from another key. And only this key keeps being changed over and over again.

Here is my example: Up is the parent of button, UpS is button being pressed which call the method from it's parent. In each parent-children it is set the same way as there. Hierarchy with the inspector - assignment of key enter image description here

On button press I call

public void ToggleChangeButtonPannel(Button button)
{
    this.ActionText.text = Description;
    this.CurrentKeyText.text = Name;

    if (Panel.enabled)
    {
        Panel.enabled = false;
    }
    else
    {
        Panel.enabled = true;
    }
}

And at update I check if panel is visible. I think the problem might be with the specification of Update() method. Does it work on every instance in parallel? If that is the case - is it possible to use Input.anyKeyDown outside the Update() method?

private void Update()
{
    if (!Panel.enabled)
    {
        return;
    }
    if (Input.anyKeyDown)
    {
        var currentKey = Key;
        try
        {
            var newKey = (KeyCode)System.Enum.Parse(typeof(KeyCode), Input.inputString.ToUpper());

            if (Shortcuts.TryChangeKeyCode(currentKey, newKey))
            {
                RenameButtons(newKey);
            }
            else
            {
                //Error message handling
            }
        }
        catch
        {
            //Error message handling
        }
    }
}

Solution

  • The problem was as I thought with Update() method. I have fixed it by using caroutine.

    public void ToggleChangeButtonPannel(Button button)
    {
        ActionText.text = Description;
        CurrentKeyText.text = Name;
    
        if (Panel.enabled)
        {
            Panel.enabled = false;
        }
        else
        {
            Panel.enabled = true;
            StartCoroutine(KeyRoutine());
        }
        EventSystem.current.SetSelectedGameObject(null);
    }
    
    
    IEnumerator KeyRoutine()
    {
        while (!Panel.enabled || !Input.anyKeyDown)
        {
            yield return null;
        }
        try
        {
            var newKey = (KeyCode)System.Enum.Parse(typeof(KeyCode), Input.inputString.ToUpper());
            if (Shortcuts.TryChangeKeyCode(Key, newKey))
            {
                RenameButtons(newKey);
                Key = newKey;
                Panel.enabled = false;
            }
            else
            {
                 StartCoroutine(RemoveAfterSeconds(3, Panel));
            }
        }
        catch
        {
            StartCoroutine(RemoveAfterSeconds(3, Panel));
        }
    }