Trying to find a way to pass Text.text from a button to a function in a script

Hey guys,

Sorry for what is most likely a complete noob question but I have been searching through the forums and google for hours and just getting frustrated.

Here is my situation, I am working on a game and have several buttons in a scene. I have a script I named LoadMap on each of the buttons that calls a method in another script to get a random building name. This random building name is then assigned to the text field of the button which works fine.

My problem is I have another script named Locations that I have added to the On Click() section in the inspector (the script is attached to a game object called MapManager that I dragged in to the box in the On Click()). It then runs a method Locations.onClicked that I wrote, I want this method to save the value from the textfield and then it loads a different scene.

The issue is that I have no way to pass that text field to the Locations script, if I set the method to take in a parameter it just gives me a text box to manually enter in something to pass to the method but I can not find a way to pass the existing string in the text field.

I have found a lot of articles online talking about using “btn.onClick.AddListener” but I cant seem to get anything to work in code with .onClick and in the documentation all I can find is http://docs.unity3d.com/ScriptReference/UI.Button-onClick.html which does not explain anything.

Please help, this is driving me crazy.

thanks.

In your script “LoadMap”, once you have changed your button name, you should do something like this :

button.onClick.AddListener(() => locations.onClicked(button));

button : is a reference to your button (LoadMap is attached on a button, ‘button’ should be a reference to “GetComponent();”).

locations : is a reference to your gameObject where Locations is attached. Either you have a public variable ‘locations’ and you set the gameObject through the inspector or you just find the gameObject in the scene view (“GameObject.FindObjectOfType();”).

onClicked(button) : is the function to call when you click on the button, with one parameter (type of Button).

Thanks I will look in to playing around with that to get it to work, so far no luck but I want to be able to do what you posted in the future.

For now I found an easy way to get it to work I did not think of, I made my onClicked method take in a gameobject and just made it public and dragged the gameobject in to the inspector.