Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Event Trigger doesn't work on instantiated prefabs

Discussion in 'UGUI & TextMesh Pro' started by TheSaviour, Aug 24, 2016.

  1. TheSaviour

    TheSaviour

    Joined:
    Apr 20, 2015
    Posts:
    68
    When I use the Pointer Up and Pointer Down triggers on a prefab that is already in the hierarchy, they work fine. But when I try to use the triggers on the same prefab when it is instantiated in the scene, they don't work.

    Any idea how to solve this?
     
  2. takatok

    takatok

    Joined:
    Aug 18, 2016
    Posts:
    1,496
    Your probably trying to use the Editor and adding a component Event Trigger. This will only work on static objects in the hierarchy. You will need to create a script that has the Event triggers init and attach the script to your Prefab
    Create a new Script (this one is C#):

    using UnityEngine;
    using UnityEngine.EventSystems;


    public class PointerTester : MonoBehaviour, IPointerDownHandler, IPointerUpHandler {

    // Use this for initialization
    public void OnPointerDown(PointerEventData eventData)
    {
    Debug.Log("Pointer is Down");
    }

    public void OnPointerUp(PointerEventData eventData)
    {
    Debug.Log("Pointer is Up");
    }
    }

    Once you have this attched to the prefab , all instantiated objects will have these handlers on them. eventData will be full of all kinds of info (mouse position, button clicked, if it was a double click, is it in the middle of a drag, etc)
     
  3. WilB

    WilB

    Joined:
    Oct 25, 2012
    Posts:
    17
    Thanks @takatok that worked perfectly well.
     
  4. kofexStudios

    kofexStudios

    Joined:
    Sep 23, 2012
    Posts:
    3
    I have this script attached to my prefab and when the prefab is instantiated, no click event is registered. Nothing prints to the console.

    However the event handlers work when the prefab is already in the hierarchy before runtime.

    Using, Unity 5.3.1f
     
    magicseth likes this.