Jak pobrać dane z klikniętego elementu w Unity

Za pomocą bilbioteki using UnityEngine.EventSystems; możemy pobrać informację na temat elementu, który został właśnie kliknięty.
W przykładzie poniżej pobierzemy materiał dołączony do przycisku i przypiszemy go do obiektu 3D.

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class BtnColor : MonoBehaviour
{
    [SerializeField] GameObject object3D;

    void Start()
    {
        this.GetComponent<Button>().onClick.AddListener(() => GetMaterial());
    }

    void GetMaterial()
    {
        // Pobiera materiał z przycisku
        Material mat = EventSystem.current.currentSelectedGameObject.GetComponent<Image>().material;

        if (mat != null)
        {
            // przypisuje materiał do obiektu 3D
            object3D.GetComponent<Renderer>().material = mat;
        }
    }
}
Ask ChatGPT
Set ChatGPT API key
Find your Secret API key in your ChatGPT User settings and paste it here to connect ChatGPT with your Tutor LMS website.
Scroll to Top