- Home /
Solved
How to get component of any button that is clicked? (Using same function for every button)
Hey everyone! I'm trying to make character selection screen. I have multiple buttons which represents different characters, also all of them has Character script attached (which is just information like name, prefab..etc...). I want to make system that will get character component from any button that is clicked, but without making multiple functions. That way, I would get prefab of that character and instantiate it in other scene.
If anyone can help, I would appreciate it.
Or if anyone has some better solution,please let me know. Thanks.
Answer by RobAnthem · Dec 10, 2016 at 05:55 PM
I'd just make a string as the reference and then you can easily get the info of your character choice by doing something like this, but maybe I'm overthinking it.
Your main area so that the data exists outside individual buttons
private string MyString;
public string myString {
get { return MyString;}
set { MyString = value; checkString();}
}
void checkString()
{
if (myString == "Warrior")
{
//do warrior stuff
}
}
and then in the button
void Start() { MyButton.onClick.AddListener(() => { MyFunction(); });
}
public void MyFunction()
{
mainData.myString = choiceList.Find(x => x.choiceName.Equals(gameObject.GetComponents<Text>().Text));
}
I've done it similar way with integers, thanks anyways! :D
Yeah numbers would likely be cleaner and take less resources since a string is the equivalent size of an integer * each character. Anyway just make your choices list an outside source and reference based on the buttons parameters. The easier parameter being the Text of the button since it is the only guaranteed difference between each button.
Answer by Kim-Nobre · Dec 11, 2016 at 11:29 PM
Create a script to store the information of the character selected, it should have the same variables as the "Character" script you attached to the buttons. Let's say the name of the script is "CharacterSelected". Then you create a function on the "Character" script called "SendCharacterSelectedInfo" (or anything else you want), this function should be called in the "OnClick" event of the buttons, and will basically do this:
void SendCharacterSelectedInfo()
{
characterSelected.name = name;
characterSelected.prefab = prefab;
}
And then you use the information on the CharacterSelected script as you like it. I hope this can help you.