1、解决UI和3D物体层叠时,只响应UI的问题
1、搭建出一个unity工程,其中UI挡在三维物体面前。
然后为三维物体挂上ColliderCube脚本,截图如下。
脚本如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ColiderCube : MonoBehaviour {
private int _index;
// Use this for initialization
void Start () {
_index = 0;
}
// Update is called once per frame
void OnMouseDown () {
ChangeColor();
}
void ChangeColor()
{
if (_index == 0)
{
GetComponent<MeshRenderer>().material.SetColor("_Color", Color.black);
}
else
{
GetComponent<MeshRenderer>().material.SetColor("_Color", Color.white);
}
_index = _index == 0 ? 1 : 0;
}
}
此时就实现了鼠标点击时只有三维物体会响应,而UI不会响应。
2、怎么让UI和物体一起响应呢?
在上面的基础上,我们在写一个脚本ColliderUI挂在UI上面就可以了。
ColliderUI脚本里实现了IPointerClickHandler接口,实现了它的OnPointerClick方法,其他代码与上面的代码差不多,如下。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class ColliderUI : MonoBehaviour ,IPointerClickHandler{
private int _index;
// Use this for initialization
void Start () {
}
public void ChangeColor()
{
if (_index == 0)
{
GetComponent<Image>().color = Color.blue;
}
else {
GetComponent<Image>().color = Color.white;
}
_index = _index == 0 ? 1 : 0;
}
public void OnPointerClick(PointerEventData eventData)
{
ChangeColor();
}
}
这样点击时就实现了当UI遮挡住三维物体时,我们点击UI,UI和三维物体同时响应鼠标,进行颜色变化的操作。
3、UI的IPointerClickHandler接口三维物体可以用么?
答:是可以的
首先呢,把物理发射器Physics RayCaster挂在相机上。
Tip:只有继承了Graphic的物体才可以响应Physics RayCaster。也就是说只有Text,image等UI可以响应。
这样我们去掉ColliderCube,然后把ColliderUI的代码复制一份给改一下改成ColliderThreeD挂在。这样当UI遮挡住三维物体时,我们点击UI,只有UI会响应,点击三维物体时三维物体才会响应。
ColliderThreeD代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class ColliderThreeD : MonoBehaviour,IPointerClickHandler{
private int _index;
// Use this for initialization
void Start () {
}
public void OnPointerClick(PointerEventData eventData)
{
ChangeColor();
}
public void ChangeColor()
{
if (_index == 0)
{
GetComponent<MeshRenderer>().material.SetColor("_Color", Color.black);
}
else
{
GetComponent<MeshRenderer>().material.SetColor("_Color", Color.white);
}
_index = _index == 0 ? 1 : 0;
}
}