I created a Canvas, then added a text UI element to it. I then attached a script to that element that has the following script. This works great.
public MyClass : IPointerEnterHandler {
public void OnPointerEnter(PointerEventData eventData) {
// This is called when the mouse enters
}
}
However, if I turn my UI element into a pre-fab, then load it at runtime, the event is never triggered. Here’s the code I use to load it at runtime:
var inventorySlot = Resources.Load("inventorySlot");
var inventorySlotObject = Instantiate(inventorySlot) as GameObject;
// inventorySpace is a GameObject field linked to this script at design time. It references a UI element where these inventorySlot items will be stuff into
inventorySlotObject.transform.SetParent(inventorySpace.transform, false);
Prefabs cannot have dynamic objects attached to it - like scripts. I’m pretty sure, your prefab among the Project folders does not have your script attached to the event trigger, only the one on your scene Hierarchy.
Do not use the prefab itself. Attach the inventorySlot gameobject to your script and instantiate this. Also, you can hide this object by deactivating it and and activate it after.
public GameObject inventorySlotObject;
public void instantiateInventorySlot() {
var inventorySlotObject = Instantiate(this.inventorySlotObject) as GameObject;
inventorySlotObject.setActive(true);
inventorySlotObject.transform.SetParent(inventorySpace.transform, false);
}
Also, I’ve recreated your case. It works just fine with prefabs.
// Handler Script
using UnityEngine;
public class Script : MonoBehaviour {
public GameObject uiObject;
public Transform uiCanvas;
void Start() {
var uiObject = Instantiate(this.uiObject) as GameObject;
uiObject.transform.SetParent(this.uiCanvas, false);
}
}
// UI Script
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class UIImage : MonoBehaviour, IPointerEnterHandler {
public void OnPointerEnter(PointerEventData eventData) {
Debug.Log("OnPointerEnter");
}
}