PhysicsRaycaster是Unity UGUI中的一個元件,用於在UI元素上進行物理射線檢測。它可以檢測滑鼠或觸控事件是否發生在UI元素上,並將事件傳遞給相應的UI元素。
PhysicsRaycaster通過發射一條射線來檢測UI元素。當射線與UI元素相交時,PhysicsRaycaster會將事件傳遞給相應的UI元素。
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class ButtonColorChanger : MonoBehaviour, IPointerClickHandler
{
private Image image;
private void Start()
{
image = GetComponent<Image>();
}
public void OnPointerClick(PointerEventData eventData)
{
image.color = Random.ColorHSV();
}
}
操作步驟:
注意事項:
using UnityEngine;
using UnityEngine.EventSystems;
public class ObjectDragger : MonoBehaviour, IPointerDownHandler, IDragHandler
{
private RectTransform rectTransform;
private void Start()
{
rectTransform = GetComponent<RectTransform>();
}
public void OnPointerDown(PointerEventData eventData)
{
rectTransform.SetAsLastSibling();
}
public void OnDrag(PointerEventData eventData)
{
rectTransform.anchoredPosition += eventData.delta;
}
}
操作步驟:
注意事項:
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class ButtonSoundPlayer : MonoBehaviour, IPointerClickHandler
{
public AudioClip soundClip;
private Button button;
private AudioSource audioSource;
private void Start()
{
button = GetComponent<Button>();
audioSource = GetComponent<AudioSource>();
audioSource.clip = soundClip;
}
public void OnPointerClick(PointerEventData eventData)
{
audioSource.Play();
}
}
操作步驟:
注意事項:
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class ButtonObjectToggler : MonoBehaviour, IPointerClickHandler
{
public GameObject targetObject;
private Button button;
private void Start()
{
button = GetComponent<Button>();
}
public void OnPointerClick(PointerEventData eventData)
{
targetObject.SetActive(!targetObject.activeSelf);
}
}
操作步驟:
注意事項:
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class ButtonSceneSwitcher : MonoBehaviour, IPointerClickHandler
{
public string targetSceneName;
private Button button;
private void Start()
{
button = GetComponent<Button>();
}
public void OnPointerClick(PointerEventData eventData)
{
SceneManager.LoadScene(targetSceneName);
}
}
操作步驟:
注意事項: