Home > Back-end >  How to get the index of an element (an array of buttons)
How to get the index of an element (an array of buttons)

Time:11-04

  • I have an array of 9 strings.
  • I also created 9 UI buttons.

Task:

  • when pressing the button [0] the line [0] appears.
  • when button [1] is pressed, line [1] appears

and so on.

using Assembly_CSharp;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using System;

public class WorldMapScr : MonoBehaviour
{
    public GameObject RoomMap;
    public TMP_Text txtHeader;
    public TMP_Text txtDescription;
    public TMP_Text txtNameRoom_1;
    public TMP_Text txtNameRoom_2;
    public TMP_Text txtNameRoom_3;
    public TMP_Text txtNameRoom_4;
    public Button[] buttons;
    allTxtRoomMap txtRoom = new();

    private void Update()
    {
        for (int i = 0; i < buttons.Length; i  )
        {
            buttons[i].onClick.AddListener(OpenWindow);
            txtHeader.text = txtRoom.headerAndDestcriptionlvl[i];
            txtDescription.text = txtRoom.headerAndDestcriptionlvl[i];
            txtNameRoom_1.text = txtRoom.roomLvlName[i];
            txtNameRoom_2.text = txtRoom.roomLvlName[i];
            txtNameRoom_3.text = txtRoom.roomLvlName[i];
            txtNameRoom_4.text = txtRoom.roomLvlName[i];
            break;
        }
    }
    void OpenWindow()
    {
        RoomMap.SetActive(true);
    }
}

I understand that the operations in the for loop don't matter because there is a "break". I sent this code only for an example, so that you understand what I want to achieve. I also want to clarify. The easiest way would be to just create a few separate methods for each button, but that's completely unprofessional in my opinion. Please tell me how this can be done with an array of buttons. Thanks for any replies.

Buttons

CodePudding user response:

You don't have to create separated methods for each button. Create one method with an integer parameter, pass this method to every Button and pass it's corresponding number as parameter. Then the appear the line with the m_textList[number] value where m_textList contains your text.

CodePudding user response:

You can add a function with parameters to the button's listener by using a delegation. Here's a small example that shows how it works with an int, but this can be applied to any type.

void Start()
{
  for (int i = 0; i < buttons.Length; i  )
  {
    int tempvalue = i;
    buttons[i].onClick.AddListener(() => Examplefunction(tempvalue));
  }
}

void Examplefunction(int i)
{
  Debug.Log(i);
}

Note that i is saved in tempvalue, which is passed to the function. This is done so that it doesn't print the Length of the button array, but rather the correct index that was set at the time.

  • Related