How do I reference button clicked to use in IndexOf
I'm trying to use a reference to a Button to get its position in a List of Buttons.
I have an OnClick function attached to multiple buttons. I have made a List of these buttons so that I can do other things with them by referencing them by their index numbers. I am having trouble figuring out how to get the index of the button that was clicked. I want to use IndexOf but I can't figure out what to use to reference the button inside of IndexOf. I have read through many pages of documentation and searched results but haven't been able to wrap my head around it.
Do I need to use AddListener? Do I need to use UnityEngine.EventSystems? Any input is appreciated. Here's an example of my script:
public void SelectThisButton() {
//try and get the index of the button pressed
buttonIndex = buttonList.IndexOf( what goes in here? );
//use the index of the button pressed for stuff
buttonSprite = buttonList[buttonIndex].GetComponent<Image>().sprite;
//do other stuff
}
Answer by TBruce · Sep 02, 2016 at 07:13 PM
Why over complicate it? If all you what to do is retrieve the sprite image from the button clicked, this will work
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class ButtonHandler : MonoBehaviour
{
public void ButtonPressed (Button button)
{
if ((button != null) && (button.image != null) && (button.image.sprite != null))
{
Debug.Log("Button image/sprite = " + button.image.sprite.name);
Sprite buttonSprite = button.image.sprite;
// do other stuff
}
}
}
You will of course have to set each button OnClick() event in the inspector like so
Here I attached ButtonHandler.cs to the canvas with all the buttons. Then on each button I first selected the Canvas. Then I selected the ButtonHandler.ButtonPressed() function. Then I selected the Button as shown in the image (in this case it was "Button (3)").
When the button is pressed the button is passed to the function where you can retrieve the sprite and do what you want with it.
If you still have a need to use a list for some reason you can do a look up based on the sprite name.
Thanks. I did get this to work and didn't need my List after all. I also made use of PlayerPrefs to store the selection so that I could make use of the data I wanted in another scene.
Your answer
Follow this Question
Related Questions
Finding all the same strings in a List 2 Answers
How to load multiple sprites at runtime from List? 1 Answer
[ANSWERED] IndexOf and LastIndexOf both returning -1 when an item is on the list. 1 Answer
Total war Style Movement System with Right Click 0 Answers
How can I check value stored in a list when pressing button with the same name? 2 Answers