UGUI学习——1、UI遮挡3D物体响应

1、解决UI和3D物体层叠时,只响应UI的问题

1、搭建出一个unity工程,其中UI挡在三维物体面前。
然后为三维物体挂上ColliderCube脚本,截图如下。
Unity工程搭建
脚本如下:

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;
    }
   
}


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值