- Home /
UI - Assigning Event Callbacks Via Script Fails on GameObjects Instantied Via Script
So I have a pretty basic tower defense game going on, there are set build points each with their own mini canvas UI for building and upgrading towers. Once you build a tower on them, they disappear and I instantiate a tower prefab with the new UI setup for upgrading said tower. Now, if I have a tower pre placed in the scene all the calls to the UI button events (set up via script) work just fine, however for whatever reason on a cloned object although all the setup script is still being called (I checked with debug statements) the events will not be called. I'm almost certain this is a bug, I'm using the latest stable version of Unity (5.3.4f1), I have my canvas set up correctly and there is an EventSystem object in the scene. Here is the button event setup script I use (it's a component on the button itself which is a child of the popup obejct on the Canvas which is a child of the actual tower object.
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using System.Collections;
public class UpgradeButtonSetup : MonoBehaviour {
public string buttonType = "";
private AttackCollector ac;
private Collector c;
private UnityEvent eButtonDown;
// Use this for initialization
void Awake () {
Debug.Log("Setting up");
eButtonDown = new UnityEvent();
// eButtonUp = new UnityEvent();
EventTrigger trigger = gameObject.GetComponent<EventTrigger>();
EventTrigger.Entry entry = new EventTrigger.Entry();
ac = transform.parent.parent.parent.GetComponent<AttackCollector>();
if(ac == null){
Debug.Log(transform.parent.parent.parent);
c = transform.parent.parent.parent.GetComponent<Collector>();
switch(buttonType){
case "hp":
eButtonDown.AddListener(c.UpgradeHp);
break;
case "resource":
eButtonDown.AddListener(c.UpgradeResourceGen);
break;
default:
eButtonDown.AddListener(c.UpgradeHp);
break;
}
}
else{
switch(buttonType){
case "hp":
eButtonDown.AddListener(ac.UpgradeHP);
break;
case "attkspeed":
eButtonDown.AddListener(ac.UpgradeAttackSpeed);
break;
}
}
entry.eventID = EventTriggerType.PointerDown;
entry.callback.AddListener((eventData) => {ButtonDown();});
trigger.triggers.Add(entry);
}
void ButtonDown(){
eButtonDown.Invoke();
}
}
Your answer
Follow this Question
Related Questions
Eventsystem requires window focus? 0 Answers
Check UI panel touched after OnEnable()? 0 Answers
How to send mouse events directly to the canvas in world pos 0 Answers
SteamVR Slider won't drag using VR Controller,SteamVR-controller can't drag Slider handle 0 Answers
Cursor.lockstate and OnPointerEnter not working together 2 Answers