如何修复 Unity/C# 中的无效表达式术语“=”错误?

Ruk*_*uku 0 c# unity-game-engine

嘿哟,对 C# 不太熟悉,更不用说 Unity了,而且我显然做错了什么,这是我的代码,我得到的唯一错误是:

'无效的表达式术语“=”

    bool currentlydown;
// further up the script
void Start() {
        currentlydown = false;
    }
// later up the script
void Update() {
if ((Input.GetKeyDown("W") || Input.GetKeyDown("A") || Input.GetKeyDown("S") || Input.GetKeyDown("D")) && currentlydown === false) {
            anim.SetBool("Walking", true);
            currentlydown = true;
        } else if (!(Input.GetKeyDown("W") || Input.GetKeyDown("A") || Input.GetKeyDown("S") || Input.GetKeyDown("D")) && currentlydown === true){
            anim.SetBool("Walking", false);
            currentlydown = false;
        }
    }
Run Code Online (Sandbox Code Playgroud)

感谢任何和所有的帮助!

Dai*_*Dai 5

  • 你正在使用===(我假设来自JavaScript?)。C# 没有===运算符,只有==.

  • JavaScript===要求操作数的类型也严格相同。C# 是静态类型的,大多数类型不能直接比较,因此===不需要运算符。

  • 此外,在比较引用类型(objectstring等)时==,运算符(默认情况下)仅检查两个操作数(它们是引用)是否指向内存中的同一个对象(几乎但不完全是指针比较)即使转换为不同的引用类型,也必然意味着类型是相同的:

    interface IFoobar {}
    class Foobar : IFoobar {};
    
    Foobar  a = new Foobar();
    Object  b = a;
    IFoobar c = a;
    
    // Even though `a` and `b` have different reference-types (`Object` vs `IFoobar`) they point to the same object in-memory, so a type-check is unnecessary.
    Console.WriteLine( b == c ); // "true"
    
    // Whereas with value-types you'll get a compiler error:
    Int32 x = 123;
    String y = "abc";
    
    Console.WriteLine( x == y ); // <-- This won't compile because Int32 and String cannot be compared.
    
    Run Code Online (Sandbox Code Playgroud)
  • 因此,更改您的代码以使用==.

  • 您还可以通过移动检查并将Input.GetKeyDown()其存储在本地bool isWasd.

就像这样:

bool currentlydown;
// further up the script
void Start()
{
    currentlydown = false;
}

// later up the script
void Update() {

    bool isWasd = Input.GetKeyDown("W")
            ||
            Input.GetKeyDown("A")
            ||
            Input.GetKeyDown("S")
            ||
            Input.GetKeyDown("D");

    if( isWasd && currentlydown == false )
    {
        anim.SetBool("Walking", true);
        currentlydown = true;
    }
    else if ( !(isWasd) && currentlydown == true ){
        anim.SetBool("Walking", false);
        currentlydown = false;
    }
}
Run Code Online (Sandbox Code Playgroud)
  • 使用bool( System.Boolean) 值时,不需要 doif( boolValue == true )if( !(boolValue == true) )or if( boolValue == false ),可以执行if( boolValue )and if( !boolValue )

就像这样:

// later up the script
void Update()
{
    bool isWasd =
        Input.GetKeyDown("W")
        ||
        Input.GetKeyDown("A")
        ||
        Input.GetKeyDown("S")
        ||
        Input.GetKeyDown("D");

    if( isWasd && !currentlydown)
    {
        anim.SetBool("Walking", true);
        currentlydown = true;
    }
    else if( !isWasd && currentlydown )
    {
        anim.SetBool("Walking", false);
        currentlydown = false;
    }
}
Run Code Online (Sandbox Code Playgroud)