Hi,
I have a problem where I’m creating new UI elements and adding text to them run-time, using a prefab and adding EventTrigger for each. For some reason, this seems to work only on the elements already part of the prefab, not on the elements instantiated from it in run-time.
This is the method used to add the triggers:
protected void AddEvent(GameObject obj, EventTriggerType type, UnityAction<BaseEventData> action)
{
EventTrigger trigger = obj.GetComponent<EventTrigger>();
if (!trigger) { Debug.LogWarning("No EventTrigger component found!"); return; }
var eventTrigger = new EventTrigger.Entry { eventID = type };
eventTrigger.callback.AddListener(action);
trigger.triggers.Add(eventTrigger);
}
Here I create the UI elements from the prefab and add the event triggers:
protected void AddEffectsAndListeners(List<string> effects, string triggerID) {
List<GameObject> effectGameObjects = new List<GameObject>();
// Use the first element from the prefab "effectHolder"
GameObject effect1 = effectHolder.transform.Find("Effect").gameObject;
Text textOfEffect1 = effect1.GetComponent<Text>();
textOfEffect1.text = effects[0];
effectGameObjects.Add(effect1);
// If there are more than one effect, add a new component to the holder for each
if (effects.Count > 1)
{
for (int i = 1; i < effects.Count; i++)
{
GameObject newEffect = Instantiate(effect1);
newEffect.transform.SetParent(effectHolder.transform);
Text textOfNewEffect = newEffect.GetComponent<Text>();
textOfNewEffect.text = effects[i];
effectGameObjects.Add(newEffect);
}
}
// Add event listeners
for(int i = 0; i < effectGameObjects.Count; i++) {
Debug.Log(triggerID + i + ". Trying to add event to " + effectGameObjects[i]);
AddEvent(effectGameObjects[i], EventTriggerType.PointerClick, delegate { PointerClick(triggerID + i.ToString()); });
}
}
And here is the handler:
protected void PointerClick(string effectID)
{
Debug.Log("Called from BP1: " + effectID);
}
I call the above method three times, first two (with triggerIDs “T” and “M”) are adding a new component to the prefab, the third (triggerID B) not. In run-time, I get this debug as expected:
However, trying to click the different elements in game yields the following:
Here are two problems:
- Only the first UI component (i.e. the one that is part of the prefab) of each AddEffectsAndListeners() method call is clickable and print to log.
- The text passed to the event handler is wrong (I would expect it to be T0, M0 and B0)
Any advice?