简体   繁体   English

Unity3D gameObject 标签对我不起作用

[英]Unity3D gameObject tag not working for me

I have this line of code, but when i run this in unity it destroys itself when comes to contact with anything, but i want to do this only when with contact with the Player.我有这行代码,但是当我统一运行它时,它会在与任何东西接触时自行破坏,但我只想在与播放器接触时这样做。 I am sure that the player tag has been assigned correctly.我确信玩家标签已正确分配。 I'm a beginner so it's probably something very dumb.我是初学者,所以这可能是非常愚蠢的事情。 Thank you for any help!感谢您的任何帮助!

if (other.gameObject.CompareTag("Player")) ;
    {
        Debug.Log("collision w/ " + other.gameObject.name);
        theScore += 50;
        scoreText.GetComponent<Text>().text = "SCORE: " + theScore;
        Destroy(gameObject);
    }

Ok, so the statements are all correct.好的,所以这些陈述都是正确的。 You just added one too many ;你加的太多了; behind the if-statement.在 if 语句后面。 If-Statements do not need a ; If 语句不需要; since the {...} ends the statements.因为{...}结束了语句。

The correct code is hence:因此正确的代码是:

if (other.gameObject.CompareTag("Player")) //no semicolon here
{
    Debug.Log("collision w/ " + other.gameObject.name);
    theScore += 50;
    scoreText.GetComponent<Text>().text = "SCORE: " + theScore;
    Destroy(gameObject);
}

Firstly, you are not supposed to add a ;首先,您不应该添加; after an if statement.if语句之后。

if (other.gameObject.CompareTag("Player")) //no semicolon here
{
    Debug.Log("collision w/ " + other.gameObject.name);
    theScore += 50;
    scoreText.GetComponent<Text>().text = "SCORE: " + theScore;
    Destroy(gameObject);
}

And if you have to destroy the gameObject collided with, then replace:如果您必须销毁与之碰撞的游戏对象,请替换:

Destroy(gameObject);

With:和:

Destroy(other.gameObject);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM