- Home /
Changing value in onClick, in button.
Is there any way to change this value on button via script:
I'm instantiating a new 'Marker' object each time the button is pressed. How can I assaign the instantiated 'Marker' GameObject into that field, after pressing the button? (I'm using Unity 5, and C#)
Answer by Strangertoyourlife · Jun 27, 2018 at 12:36 PM
Tried to do something similar and ended up using delegate:
public Button testButton;
public Transform marker;
void Start () {
testButton.onClick.AddListener(delegate {ButtonPressed(marker);});
}
public void ButtonPressed(Transform mark)
{
Debug.Log(mark);
}
This will create a new listener in "On Click ()" at the Start. It will then assign its value to be "Marker" so whenever the button is pressed it will pass though "Marker".
"void Start ()" can easily be altered to something else and you can change the marker to anything as long as it is the same type of requirement the function has. If you want to remove the listener before adding a new listener then you could use testButton.onClick.RemoveAllListeners
or testButton.onClick.RemoveListeners
Your answer
![](https://koobas.hobune.stream/wayback/20220613200541im_/https://answers.unity.com/themes/thub/images/avi.jpg)