- Home /
Accessing one script on multiple gameObjects?
Hi,
I have a script that is attached to multiple gameObjects. I want to access a specific function in this script on any of the GameObjects it is attached to when clicking on a button.
The problem is as far as I know if I do want to access a script from another script I have to reference it in the beginning and then add the function I want to use OnClick(). Something like this
[SerializeField]
ScriptIWantToAccess ABC;
public void OnClickForButton()
{
ABC.MyFunction ();
}
After that I have to drag the GameObject that ABC is attached to into the inspector. The thing is that if I have multiple GameObjects with this script and I want to access all of them when pressing the button using my way I would need x amount of [SerializeField]...
to then drag all of them individually into the inspector which would simply be insane...
If someone is able to help out on how to do this would be awesome. If anything is unclear please let me know :)
Thanks in advance.
Answer by misher · Sep 11, 2018 at 01:55 PM
You need to keep track of all objects somewhere. Say you have all them inside some parent in hierarchy, on this parent gameobject you should attach another new script (like a manager), then your button can activate a method in this manager script which in turn will grab all ABC children and call methods inside those ABC scripts:
public class Manager : MonoBehaviour {
/// this method is for button
public void ClickMethod() {
foreach(var abc in GetComponentsInChildren<ABC>()) {
abc.MyFunction();
}
}
}
public class Manager : MonoBehaviour {
public void MyFunction() {
}
}
Answer by PizzaPie · Sep 11, 2018 at 02:06 PM
First of all you should use an Array or list of wanted type. I ll assume the object that has the OnClick method is a single instance. So you may:
Make use FindObjectOfType to populate the array (viable if used only once, would not support adding new instances on runtime, generally disliked method)
Or reverse the process and use FindObjectOfType inside the ABC script to find the OnClick instance and add themselfs on the array or the event (as mentioned below)
Make the OnClick Script a Singleton and then have the ABC instances add themselfs on the Array
Same as above but instead of using an Array with direct references use EventHandlers and add them on the onClick event of the button via the Singleton OnClick Script
Drag and drop editor fun. (non viable)
bit far fetched but you could use the Event Aggregator pattern (message system). (Don't bother with this yet)
Cheers
Your answer
![](https://koobas.hobune.stream/wayback/20220612174413im_/https://answers.unity.com/themes/thub/images/avi.jpg)