Quicki Quicki - 1 year ago 349
C# Question

onClick event for Image in Unity

Is it possible add "onClick" function to an Image (a component of a canvas) in Unity ?

var obj = new GameObject();
Image NewImage = obj.AddComponent<Image>();
NewImage.sprite = Resources.Load<Sprite>(a + "/" + obj.name) as Sprite;

How can I add action for "onClick" event?

Answer Source

I suppose that ClickAction is your script. It could look something like this:

using UnityEngine.EventSystems;

public class ClickAction : MonoBehaviour, IPointerClickHandler
    public void OnPointerClick(PointerEventData eventData)
        // OnClick code goes here ...

The namespace UnityEngine.EventSystems supplies you with the IPointerClickHandler interface. When your image is clicked, the code inside OnPointerClick will run.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download