1
\$\begingroup\$

i have a grid layout group containing buttons. My game must be playable with a joystick and so I have to navigate the buttons using horizontal/vertical input.

My problem right now is when the layout group first becomes visible. Once I click on a button (with my mouse), it becomes "selected" and I can navigate through the layout group with my keyboard and 'click' with spacebar. This functionality is all fine, except for the need to click the button with a mouse to set the first selection.

I've tried both of the following:

void buttonClicked() {
    Debug.Log("clicked");
}

void Start () {
  // this button is actually instantiated from a prefab,
  // not shown here
  Button btn = inventorySlot.button;

  btn.onClick.AddListener(buttonClicked);

  # attempt 1
  btn.Select();

  # attempt 2
  eventSystem.SetSelectedGameObject(
    btn.gameObject,
    new BaseEventData(eventSystem)
  );
}

both these commands do select the button, but they also inadvertently call the onClick, and the button is clearly being clicked because it changes color (I have configured this through button opts in the inspector).

My question is - how can I "select" the button without clicking it?

I perhaps should also note, I am populating the layout group with buttons at runtime. Each button is intantiated from a prefab in Start() (not showing that here). I only add the event listeners and try to select the button after it's already added to actual game objects in my scene.

\$\endgroup\$
1
\$\begingroup\$

Figured it out, the issue was that I call btn.Select() before the menu is actually open, and space is also the command to show the menu. So basically I need to put the btn.Select() after the menu is visible.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.