- Home /
Add Separate Button Listeners to Prefabs on Runtime
I've got a problem where my button onClick.AddListener function is getting overwritten when I instantiate a new prefab and add a listener to the new prefab.
public GameObject LatestPrefab;
public Button CreatePrefabBut;
//Method called when button is clicked
public void CreateNewPrefabOnClick() {
LatestPrefab = Instantiate(Prefab);
//Add new onClick event to trigger a method on the Prefab
CreatePrefabBut.onClick.AddListener(() => {
LatestPrefab.GetComponent<ScriptOnPrefab>().Move();
});
}
As far as I can tell, every time I instantiate a new prefab it overwrites the onClick on the previous prefab and therefore doesn't call the method when the button is clicked.
Any help would be appreciated. Thanks.
Comment