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

Unity can't identify which button is beeing pressed


I've been trying to make the options in my game being selected by a keyboard input. I can highlight them, but I don't know how to make Unity identify which of the buttons is beeing pressed in order to do a certain action, it's giving me the NullReferenceException in line 28 of my code. The cript in question is the BattleSystem script, it's attached to the event system, the battleFirstButton is the fight button and the enterKey is "Z".

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class BattleSystem : MonoBehaviour
{
    public GameObject battleFirstButton;

    public KeyCode enterKey;
    Button selectedButton;

    // Start is called before the first frame update
    void Start()
    {
        EventSystem.current.SetSelectedGameObject(null);
        EventSystem.current.SetSelectedGameObject(battleFirstButton);
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(enterKey))
        {
            selectedButton.onClick.Invoke();
        }  
    }

    public void SetSelectedButton()
    {
        selectedButton = GetComponent<Button>();
    }

    public void Fight()
    {
        print("Fight option submitted");
    }

    public void Act()
    {
        print("Act option submitted");
    }

    public void Item()
    {
        print("Item option submitted");
    }

    public void Mercy()
    {
        print("Get dunked o-, I mean, Mercy option selected");
    }
}

enter image description here

The four buttons OnClick() functions

enter image description here


Solution

  • selectedButton is a private variable potentially never set to anything, so it's null. Make sure it's set to something before you access it.

    Probably the simplest fix to the way you have it set up is:

    void Update()
    {
        if (Input.GetKeyDown(enterKey))
        {
          // Gets the focused button
          selectedButton = EventSystem.current.currentSelectedGameObject.GetComponent<Button>();
          if (selectedButton != null) 
          {
              selectedButton.onClick.Invoke();
          }
    }