我做错了什么?我如何让游戏对象传递相同的颜色并销毁不同的颜色


Color[] colors = new Color[] { Color.cyan, Color.red, Color.yellow, Color.magenta };
private int currentColor, length;
void Start()
{
currentColor                            = 0; //White
length                                  = colors.Length;
GetComponent<Renderer>().material.color = colors[currentColor];
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
currentColor                            = (currentColor + 1) % length;
GetComponent<Renderer>().material.color = colors[currentColor];
}
}
void OnTriggerEnter2D(Collider2D col)
{
if (col.tag != currentColor)
{
Destroy(col.gameObject);
}
}

我想做的是让游戏对象通过相同的颜色,并在通过不同颜色的时销毁

如果你在碰撞col.GetComponent<Renderer>().material.color上检查颜色,如果它不等于colors[currentColor],玩家会死。

用实际颜色检查游戏对象:

void OnTriggerEnter2D(Collider2D col) 
{
// Check if color of the collided GameObject is equal to the current color of the Player
if(col.GetComponent<Renderer>().material.color != colors[currentColor])
{
// Destroy Player because he collided with an obstacle
Destroy(gameObject);
} 
}

检查带有标签的游戏对象:

void OnTriggerEnter2D(Collider2D col) 
{
// Check if color of the collided GameObject is equal to the current color of the Player
// Use CompareTag to get an Error Message when the Tag doesn't exist
if(!col.CompareTag(currentColor))
{
// Destroy Player because he collided with an obstacle
Destroy(gameObject);
} 
}

简单的tagstringcurrentColor是整数。你不能做

col.tag != currentColor 

我不明白的是,你是如何编译它的,它不应该按照它的编写方式工作。

无论如何,如果你坚持使用标签,你的代码可以这样重写:

System.Tuple<Color, string>[] colors = new System.Tuple<Color, string>[] {
new System.Tuple<Color, string> (Color.cyan, "cyan"),
new System.Tuple<Color, string> (Color.red, "red"),
new System.Tuple<Color, string> (Color.yellow, "yellow"),
new System.Tuple<Color, string> (Color.magenta, "magenta")
};
private int currentColor, length;
void Start () {
currentColor = 0; //White
length = colors.Length;
GetComponent<Renderer> ().material.color = colors[currentColor].Item1;
}
void Update () {
if (Input.GetMouseButtonDown (0)) {
currentColor = (currentColor + 1) % length;
GetComponent<Renderer> ().material.color = colors[currentColor].Item1;
}
}
void OnTriggerEnter2D (Collider2D col) {
if (col.tag != colors[currentColor].Item2) {
Destroy (col.gameObject);
}
}

附言:这会起作用,但如果我是你,我根本不会在这个案子上使用标签。

最新更新