- Home /
Get ID of clicked button from array
Good day
Stupid question but I stuked at this for hours -_-
I have ButtonManager.cs that is attached to an empty object
This script have an array of 5 buttons
I want to find the array index of clicked button so when I click on the button I can change button alpha
It work well. Alpha is changing but it's changing on all buttons at the same time so I need to get te currentButtonID and assign it to this another array with images..
Well...How can I get the current clicked button index?
Any suggestions?
Thank you
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ButtonManager: MonoBehaviour {
public RectTransform[] buttons;
private Image[] _btnImg;
private int curBtnID;
// Use this for initialization
void Start ()
{
_btnImg = new Image[tabButtons.Length];
for (int i = 0; i < tabButtons.Length; i++) {
_btnImg [i] = tabButtons [i].GetComponent <Image> ();
_btnImg [i].CrossFadeAlpha (0f, 0f, false);
}
}
public void Trigger_ButtonClick()
{
for (int i = 0; i < tabButtons.Length; i++)
{
_btnImg [i].CrossFadeAlpha (1f, 1f, false);
}
}
}
You can try to check the name of the current clicked Button ,but that means all Buttons should have different names.
For this you have to change the code $$anonymous$$imally :
public void Trigger_ButtonClick(string InputName)
{
for (int i = 0; i < tabButtons.Length; i++)
{
if(_btnImg [i].name == InputName)
{
CurBtnID = i;
break;
}
}
_btnImg [CurBtnID].CrossFadeAlpha (1f, 1f, false);
}
Now you just copy the Inspector name of the Button into the free space next to your Gameobject with the Button$$anonymous$$anager. And it should work :D
oh. of course. nice idea I change the script a bit so I'm taking the ID ins$$anonymous$$d of name
like this
public void Trigger_ButtonClick(int btnID)
{
for (int i = 0; i < tabButtons.Length; i++)
{
if(i == btnID)
{
CurBtnID = i;
}
}
_btnImg [CurBtnID].CrossFadeAlpha (1f, 1f, false);
}
looks to work thank you
Your answer

Follow this Question
Related Questions
C# For loop in button to set gameObjects in array to active 1 Answer
Distribute terrain in zones 3 Answers
Call a variable from each game object in an array? 1 Answer
Button array c# 0 Answers