- Home /
Call a function across several objects
Hi, all! I have 8 buttons that need to refresh themselves whenever one of them is selected. I was baffled for a while at my problem, and then after extensive debugging, realized that I was only calling the 'refresh' function on the button that was clicked.
Is there a way for me, when one button is clicked, to call a function that exists on the 7 other buttons?
Thanks! - YA
The closest thing I could find was $$anonymous$$essaging, but it doesn't quite fit my situation...
Answer by Michael CMS · Nov 05, 2012 at 02:09 PM
The best approach (in my opinion) is to have a ButtonManager that keeps track of all the buttons instantiated in a list, then you can iterate through the buttons and call the refresh function for each. Keeping references stored somewhere of each button will be the fastest and cleanest way.
Here's some code
class ButtonManager
{
static List<Button> InstantiatedButtons= new List<Button>();
public static void RefreshButtons()
{
for (int i=0;i<InstantiatedButtons.Count;i++)
InstantiatedButtons[i].Refresh();
}
public static Button CreateButton()
{
Button but = new Button();
InstantiatedButtons.Add(but);
return but;
}
}
You will have to instantiate all Buttons through the ButtonManager thou.
This is one approach. Another would be for each Button on Start/Awake to register themselves into the button Manager.
Another thing that you can do (but it will be slow) is to find all elements of type button from the scene and call the refresh for them.
Button[] buttons = GameObject.FindSceneObjectsOfType(typeof (Button));
for (int i=0;i<buttons.length;i++)
buttons[i].Refresh();
I am working in Javascript, and I vaguely understand what is going on here, but if you have the time, could you please tell me what is going on precisely? I don't want to miss anything.
Your answer
Follow this Question
Related Questions
Camera Move 1 Answer
Why pass parameters into a function? 2 Answers
Source code for library function "RecalculateNormals()"? 4 Answers
Array Problem - Error Code BCE0022 1 Answer