本文将从游戏物体(Gameobject),和UGUI,讲解Unity—PC端开发中,鼠标事件的常见功能实现
本文将帮你解决Unity中如下或者类似的事件响应问题:
游戏物体篇
- 点击游戏物体,物体消失;
- 鼠标悬停在游戏物体上,物体旋转;
- 移入游戏物体,游戏物体变大;
- 离开游戏物体,游戏物体变小
UGUI篇
- 点击按钮响应事件
- 移入UI组件
- 移出UI组件
【由于本文章重点在讲解鼠标事件响应,所以基本操作这里博主不做赘述。】
对于游戏物体
游戏物体的事件响应相对于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组件
由于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上面操作:
利用此方法,你可以实现任何你想实现的功能!
接下来是移入、移出事件:
在这里我们需要借助两个接口:
IPointerEnterHandler
可以实现如下方法
public void OnPointerEnter(PointerEventData eventData) //鼠标移入
IPointerExitHandler
可以实现如下方法
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)上。
至此,大功告成!
*