我有一个对象(球体(,它在单击时会改变其颜色(蓝色,绿色,黄色,红色(。另一个物体(立方体(每 3 秒生成一次并与球体碰撞,但结果会根据球体的颜色而有所不同。我正在使用材质来改变球体的颜色。
但是我找不到一种方法来检查 CUBE 是否与 SPHERE 碰撞,当它是蓝色、绿色、黄色或红色时。
最好的选择是设置一个颜色变量,并在每次颜色更改时更改它。然后,当您的立方体命中它时,只需比较变量即可。我改变材料的方式对我来说只是一个简单的方法。您可以以任何您想要的方式更改它,只需保持索引不变即可。您可以使用此代码来执行此操作。
在球体上
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpriteCColor : MonoBehaviour {
public Material[] materials;
public Renderer rendBlock;
public int index = 1;
// Use this for initialization
void Start () {
rendBlock = GetComponent<Renderer>();
rendBlock.material.SetColor(5, Color.red);
}
// Update is called once per frame
void Update () {
/*
when index =
1 = red
2 = yellow
3 = green
4 = blue
*/
if (Input.GetMouseButtonDown(0)) {
index += 1;
if (index == materials.Length +1) {
index = 1;
}
//print(index);
if (index == 1)
{
rendBlock.material.SetColor(5, Color.red);
}
if (index == 2)
{
rendBlock.material.SetColor(5, Color.yellow);
}
if (index == 3)
{
rendBlock.material.SetColor(5, Color.green);
}
if (index == 4)
{
rendBlock.material.SetColor(5, Color.blue);
}
}
}
}
在你的立方体上,你可以把这个:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Senes : MonoBehaviour {
public SpriteCColor A;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnCollisionEnter(Collision collision)
{
A = collision.gameObject.GetComponent<SpriteCColor>();
if (A.index == 1)
{
Debug.Log("Red");
}
else if (A.index == 2)
{
Debug.Log("Yellow");
}
else if (A.index == 3)
{
Debug.Log("Green");
}
else if (A.index == 4)
{
Debug.Log("Blue");
}
}
}