I'm attempting to add events to buttons on a menu that is assembled at run time.
// The rest of the menu is assembled around this. There is a 'foreach' loop adding the buttons one at a time.
GameObject obj = Instantiate(quickCommandPrefab, FindCorrectHolder(c.cType).transform);
// >>>
// There are other things happening here that aren't having problems.
// >>>
// set the event for the "button press"
btn = obj.transform.GetComponent<Button>();
btn.onClick.RemoveAllListeners();
btn.onClick.AddListener(delegate { CheckKeyPress(c.keyToActivate); });
// There is just something about the button onClick event.
I have tried multiple slightly different syntax that still amounted to this.
These are the components of the object being instantiated.
I have even gone so far as to separate out that code into its own function to execute separately after the instantiation as follows:
void SetupButtonEvents()
{
foreach (Button btn in transform.GetComponentsInChildren<Button>(true))
{
Button temp = btn; // I did try a temp variable as well to see if that would help. NOPE, same problem!
string keyCode = btn.transform.Find("UseKeyText").GetComponent<TextMeshProUGUI>().text;
btn.onClick.RemoveAllListeners();
btn.onClick.AddListener(delegate { CheckKeyPress(Enum.Parse<KeyCode>(keyCode)); });
}
}
I've been using 'Debug.LogWarnings' to track what is going on and btn.onClick.GetPersistentEventCount() always comes back 0.
I can't say as I've had this problem before, though that is usually without Unity's own event system or using said event system through the inspector and not through code.

AddPersistentListener