passing gameobject to button parameter?

I have a button which is used to call a function from a script on an object. However I have multiple objects that use that script, and I want to button to work with each of them. Currently I just have the one gameobject dropped into the on Click parameter of the button, so the button only works for the one object. Is there a way that each object can send themselves to the button parameter?

I was trying something along the lines of, UI.GetComponenet(). something and pass the object there. But there is no function that seems to allow this

You can use the AddListener() method to dynamically add listeners to UI buttons and other UI Components that send off messages via UnityEvents.

1 Like

I have combined your answer with a few other things I found online, but it still does not seem to be working. Am I doing this correctly? Nothing seems to be getting assigned in the inspector

GetComponent<Button>().onClick.AddListener(() => { Searching(this.gameObject); });


 public void Searching(GameObject SearchObj)
    {
        Debug.Log("search");
       
    }

You won’t see that listener added. The inspector can only “see” what can be serialized.

But is it working? It certainly works so review what you have done if it doesn’t.

Make a blank scene, put a button in, make a script, add your listener, it DOES work.

1 Like

Just to make sure I have explained the issue correctly, so I am not debugging code that is not a solution to my problem I would like to just explain the problem better.

I have 20 game objects. Each of these have access to a canvas which has a button. This button is used to enable an image, so when the button is clicked, it calls a function that checks if a variable is true or not. Therefore I need this button to have access the function on each of these objects. Currently It is assigned one game object in the inspector, so it is currently only working with that one object. The above code should work for this then?

Also just so I know, how is the button being updated with each game object using this code. From what I can tell, it is simply calling a function and passing itself to that function, but no where is the button parameter updated?

You could add each of those 20 objects to the button but that seems silly. Why not make a script that:

  • has the function that the button calls

  • does the boolean check you mention

  • has an array of GameObject[ ] in it that it sets

Perhaps I’m not getting what you’re trying to do, but the less you do with the actual Button the better, because then you control it explicitly in your code and can debug it.

1 Like