5

I hope my question is not duplicate; I have a lot of Gameobjects in unity. i need to add onclicklistener in runtime to a game object with script...

please help.

Ludovic Feltz
  • 11,416
  • 4
  • 47
  • 63
ali karimifard
  • 115
  • 2
  • 13

1 Answers1

9

Here is a code that add an EventTrigger at runtime:

YourGameObject.AddComponent(typeof(EventTrigger));
EventTrigger trigger = YourGameObject.GetComponent<EventTrigger>();
EventTrigger.Entry entry = new EventTrigger.Entry();
entry.eventID = EventTriggerType.PointerClick;
entry.callback.AddListener( (eventData) => { /* Your code here */ });
trigger.triggers.Add(entry);
Toastrackenigma
  • 7,604
  • 4
  • 45
  • 55
Ludovic Feltz
  • 11,416
  • 4
  • 47
  • 63
  • 2
    While this is correct, it's worth noting that you should implement `IPointerDownHandler` in a script then attach that script to a GameObject during run-time. `EventTrigger` is known to be be slow when attached to a GameObject especially on mobile devices. – Programmer Oct 02 '17 at 14:23
  • 1
    @Programmer Thank you for pointing that out :) – Ludovic Feltz Oct 02 '17 at 14:27
  • Np but this answer should be known too so I up-voted to make sure that it is not deleted. – Programmer Oct 02 '17 at 14:29
  • @LudovicFeltz hi ludvic ....i use this sulotion but dont work for me – ali karimifard Oct 02 '17 at 17:15
  • @LudovicFeltz my code : GameObject.Find ("r1").AddComponent(typeof(EventTrigger)); EventTrigger trigger = GameObject.Find ("r1").GetComponent (); EventTrigger.Entry entry = new EventTrigger.Entry (); entry.eventID = EventTriggerType.PointerClick; entry.callback.AddListener ((eventData) => {Debug.Log ("on click attached");}); trigger.triggers.Add (entry); – ali karimifard Oct 02 '17 at 17:16
  • @LudovicFeltz I use your sulotion in a coroutine... – ali karimifard Oct 02 '17 at 17:24
  • @Programmer hi my brother.......please help that solution do n't work for me – ali karimifard Oct 02 '17 at 18:15
  • @alikarimifard The code in this answer should work. The code in the duplicate answer should also work. If not, please add "EDIT" in your question and add the code that you used that did not work for you. – Programmer Oct 02 '17 at 18:25
  • @EmerE please help – ali karimifard Oct 02 '17 at 18:57