Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add onclick listener to a gameobject in runtime In unity [duplicate]

Tags:

c#

unity3d

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.

like image 349
ali karimifard Avatar asked Oct 02 '17 14:10

ali karimifard


People also ask

What is add listener in unity?

Use UnityEvent. AddListener to extend the onClick click events. The added UnityAction is called when the Button press is released. A Button can have multiple listeners. As an example, in the script example below, btn3 can have TaskOnClick added as a second listener call.

How do you create a new GameObject during runtime?

In order to create an empty game object, the only thing that you need to do is to create an instance of GameObject using the new keyword. GameObject obj = new GameObject( ); GameObject obj = new GameObject( );

How do you copy on GameObject?

copy = new gameobject(); copy = original; copy.


Video Answer


1 Answers

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);
like image 102
Ludovic Feltz Avatar answered Nov 14 '22 19:11

Ludovic Feltz