- Home /
listeners not working on dont destroy on load object
Never used listeners before so I might just be not understanding how the work properly? But what's happening, is I add a listener to a button every time a specific scene is loaded.
Here is a list of events that stop it working: -When I first run the game, the listener works as intended, the buttons are created in the script, and the listener is added. -I change the scene, not destroying the object with the script containing the listener. -When the scene changes back, the script will re-create the buttons, and re-add the listener to the buttons. -Using a simple log to check the method the listener should run, the log will no longer show.
Where I create the listeners! csharp: foreach (Sprite texture in spriteImages) {
//Creates a button
GameObject button = Instantiate (shopButtonPrefab) as GameObject;
// gets the buttons image compnent for changing
Image buttonImage = button.GetComponent<Image> ();
Image[] images = button.GetComponentsInChildren<Image>();
int newIndex = spriteIndex;
button.GetComponent<Button> ().onClick.RemoveAllListeners ();
button.GetComponent<Button> ().onClick.AddListener (() => ChangePlayerSkin (newIndex));
spriteIndex++;
foreach (Image image in images) {
if (image != buttonImage) {
image.sprite = texture;
// Uses a bit shift to check if it has been bought
button.transform.GetChild (2).gameObject.SetActive (false);
if((skinAvailability & 1 << index) == 1 << index)
{
//Turns off overlay for unbought item
button.transform.GetChild (1).gameObject.SetActive(false);//shopButtonContrainer.transform.GetChild (currentSkinIndex).GetChild (1).gameObject.SetActive (false);
skinPurchased[index] = true;
}
if (currentSkinIndex+1 == spriteIndex) {
button.transform.GetChild (2).gameObject.SetActive (true);
}
index++;
break;
}
button.transform.SetParent (shopButtonContrainer.transform, false);
button.transform.GetChild (1).GetChild(0).GetComponent<Text> ().text = (skinCosts[spriteIndex-1].ToString());
shopButtons.Add (button);
}
What the listener should call: Code (CSharp): private void ChangePlayerSkin(int index){
selectedSkinIndex = index; Debug.Log ("noo"); if (skinPurchased [index]) { currentSkinIndex = index;
foreach (GameObject button in shopButtons) {
button.transform.GetChild (2).gameObject.SetActive (false);
}
shopButtons [currentSkinIndex].transform.GetChild (2).gameObject.SetActive (true);
}
}
// Stops working after the scene is re-loaded
Only trying to show relevant code. The buttons are created in OnSceneLoaded method every time a certain scene is run. Then the listener is added. Why will the listener only work the first time the scene is loaded? And not every time the scene is reloaded. Does the dontdestroyonload mess up the listener?
Your answer
![](https://koobas.hobune.stream/wayback/20220612190204im_/https://answers.unity.com/themes/thub/images/avi.jpg)