主要使用的是UI中IPointerClickHandler接口 实现Image和Cube点击后改变颜色,但是互相不会影响
在Unity中创建我们的两个“主角”,层叠摆放
注意Cavas'的设置
创建UIImage脚本挂在到IImage上
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class UIImage : MonoBehaviour, IPointerClickHandler
{
private Image _image;
int index = 0;
private void Start()
{
_image = GetComponent<Image>();
}
public void OnPointerClick(PointerEventData eventData)
{
ChangeColor();
}
void ChangeColor()
{
if (index == 0)
{
_image.color = Color.red;
}
else
{
_image.color = Color.black;
}
index = index == 0 ? 1 : 0;
}
}
创建ChangeCubeColor挂载到Cube上
因为ChangeCubeColor需要实现UI中IPointerClickHandler接口所以需要在Main Camera上添加Physics Raycaster组件
运行Unity 鼠标左键点击Image后只有Image会变色 点击Cube只有Cube会变色