游戏物体的事件响应相对于UI组件,较简单。只需要记住这几个函数便可以:
private void OnMouseDown() //鼠标按下
private void OnMouseEnter() //鼠标移入物体
private void OnMouseOver() //鼠标悬停时每帧调用
private void OnMouseExit() //鼠标移出
下面我们来看看下面的效果是如何实现的:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Collider_Test : MonoBehaviour
{
public Text T;
// Start is called before the first frame update
private void OnMouseDown() //鼠标按下
{
Destroy(this.gameObject);
T.text = this.gameObject.name + "被销毁!";
}
private void OnMouseEnter() //鼠标移入物体
{
this.transform.localScale = new Vector3(1.5f, 1.5f, 1.5f);
}
private void OnMouseOver() //鼠标悬停时每帧调用
{
this.transform.Rotate(new Vector3(10, 10, 10) * Time.deltaTime);
T.text = this.gameObject.name + "在旋转!";
}
private void OnMouseExit() //鼠标移出
{
T.text = "离开了" + this.gameObject.name;
this.transform.localScale = new Vector3(1.0f, 1.0f, 1.0f);
}
}
我们只要把这些代码挂载到我们想要进行事件响应的游戏物体上就可以了。
注意!!!!
这些功能函数都无法离开碰撞体(Collider)的支持
由于UI组件太多,这里只讲解Button,其他的可以以此类推,这里博主不做重述。
同样的,我们来看看我们实现的效果:
点击事件需要我们编写点击事件:这里需要从新创建一个脚本,这里我们的创建TEst.cs脚本
内容如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TEst : MonoBehaviour
{
public Text TT;
public void ButtonEvents()
{
TT.text = "点击事件:销毁!";
Destroy(this.gameObject);
}
}
把他挂载到我们场景的Cube游戏物体上:
接下来,我们在Button上面操作:
利用此方法,你可以实现任何你想实现的功能!
在这里我们需要借助两个接口:
可以实现如下方法
public void OnPointerEnter(PointerEventData eventData) //鼠标移入
可以实现如下方法
public void OnPointerExit(PointerEventData eventData) //鼠标移出
我们创建脚本 UI_Test:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class UI_Test : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
public Text T;
public void OnPointerEnter(PointerEventData eventData) //鼠标移入
{
T.text = "鼠标移动到了" + this.name;
}
public void OnPointerExit(PointerEventData eventData) //鼠标移出
{
T.text = null;
}
}
我们把这个脚本分别挂载到我们的Button和Button(1)上。
// 按钮抬起的时调用此方法
public void OnPointerUp (PointerEventData eventData)
{
}
// 按钮被按下后调用此方法
public void OnPointerDown (PointerEventData eventData)
{
}
使用方法和上面接口类似
*