Accessing one script on multiple gameObjects?


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

  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 :slight_smile:

Thanks in advance.

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>()) {
public class Manager : MonoBehaviour {
    public void MyFunction() {

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:

  1. Make use FindObjectOfType to populate the array (viable if used only once, would not support adding new instances on runtime, generally disliked method)
  2. 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)
  3. Make the OnClick Script a Singleton and then have the ABC instances add themselfs on the Array
  4. 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
  5. Drag and drop editor fun. (non viable)
  6. bit far fetched but you could use the Event Aggregator pattern (message system). (Don’t bother with this yet)