Unity Debug Error: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement

Unity Debug Error: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement

我正在尝试创建一个 2D 击球游戏。我想访问位于另一个脚本中的 int 变量 (public int ScoreTask = 10;)。但是,当我调试代码时,出现以下错误:

error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement

error CS0103: The name `ScoreTask' does not exist in the current context

这是我的脚本:

public class Countdown : MonoBehaviour 
{   
    private Ball scoreScript;
    public GameObject ScoreBoard;

    void Start () 
    {
        scoreScript = ScoreBoard.GetComponent<Ball> ();
    }
    void Update () 
    {
        GetScore ();
    }
    void GetScore() 
    {
        scoreScript.ScoreTask;

        if (timeLeft == 0 && ScoreTask != 0)
            Application.LoadLevel("GameOver");
    }
}

只需执行:

void GetScore() 
{
    if (timeLeft == 0 && scoreScript.ScoreTask != 0){
        Application.LoadLevel("GameOver");
    }
}

问题是你问的是 ScoreTask 在你的 if 条件下是什么,但它不知道 ScoreTask 是什么,没有它来自哪里的上下文,即 scoreScript.ScoreTask

另一种解决方案,如果您希望将其存储为变量:

void GetScore() 
{
    int scoreTask = scoreScript.ScoreTask;
//  ^^^ because we are "declaring" or creating the variable, we have to specify what 
//      type of variable it is. That is the only time we have to do that. 

    if (timeLeft == 0 && scoreTask != 0)
        Application.LoadLevel("GameOver");
}

另一个选项:

private int ScoreTest { get { return scoreScript.ScoreTask; } }
//          ^^^ This is a property, and is effectively a function. 
// It's body will get called everytime someone tries to read its value

void GetScore() 
{
    if (timeLeft == 0 && ScoreTask != 0)
        Application.LoadLevel("GameOver");
}

相对于字段 属性 的优势在于,如果我确实将分值存储在 scoreTask 中并且 scoreScript.ScoreTask 更改,我现在将错误的值存储在 scoreTask 因为我只有原始值的 copy,所以每次我想使用它时我都必须更新 scoreTask 以确保我不是使用过时的值。

但是,在这种用法中,属性将始终提供最新的值,我们无需担心。还有:

void Test()
{
    scoreScript.ScoreTask = 0;
    int scoreTask = scoreScript.ScoreTask;

    scoreTask = 1;
    Debug.Log(scoreScript.ScoreTask);     // prints 0
    Debug.Log(scoreTask);                 // prints 1
}

我们所做的只是更改 copy 的值,而不是原始值。我向您展示的 属性 会阻止您实际设置值并引发编译错误。如果没有 类 有任何业务设置该值,这很好。但如果我们这样做:

int ScoreTask
{
    get { return { scoreScript.ScoreTask; }
    set { scoreScript.ScoreTask = value;  } 
}

现在,如果我们这样做 ScoreTask = 1; 它实际上会改变原始值。