OnClick event for image in Unity

Is it possible to add the "onClick" function to an image (canvas component) in Unity?

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

How to add action for onClick event?

+4
source share
1 answer

I suppose that ClickActionis your script. It might look something like this:

using UnityEngine.EventSystems;

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

The namespace UnityEngine.EventSystemsprovides you with an interface IPointerClickHandler. When your image is clicked, the code inside OnPointerClickwill be launched.

+11
source

Source: https://habr.com/ru/post/1660600/


All Articles