本文实例为大家分享了Unity通过代码修改按钮点击效果的具体代码,供大家参考,具体内容如下
效果:
创建一个脚本,挂载到按钮上,主要是实现鼠标移入、移出、按下、抬起等事件的接口
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class ButtonChangeColor : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IPointerDownHandler,IPointerUpHandler
{
private Text m_Text;
private Image image;
public Sprite[] sprites;
void Awake()
{
m_Text = transform.Find("Text").GetComponent<Text>();
image = GetComponent<Image>();
}
/// <summary>
/// 鼠标移入事件
/// </summary>
/// <param name="eventData"></param>
public void OnPointerEnter(PointerEventData eventData)
{
image.sprite = sprites[1];
m_Text.color = Color.red;
}
/// <summary>
/// 鼠标移出事件
/// </summary>
/// <param name="eventData"></param>
public void OnPointerExit(PointerEventData eventData)
{
image.sprite = sprites[0];
m_Text.color = Color.black;
}
/// <summary>
/// 鼠标按下事件
/// </summary>
/// <param name="eventData"></param>
public void OnPointerDown(PointerEventData eventData)
{
image.sprite = sprites[2];
m_Text.color = Color.white;
}
/// <summary>
/// 鼠标抬起事件
/// </summary>
/// <param name="eventData"></param>
public void OnPointerUp(PointerEventData eventData)
{
image.sprite = sprites[0];
m_Text.color = Color.black;
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。