嘿,對 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;
}
}
任何和所有的幫助表示贊賞!
uj5u.com熱心網友回復:
您正在使用
===(我假設來自 JavaScript?)。C# 沒有===運算子,只有==.JavaScript
===為了要求運算元的型別也嚴格相同。C# 是靜態型別的,大多數型別不能直接比較,因此===不需要運算子。此外,在比較參考型別(
object、string等)時,==運算子(默認情況下)僅檢查兩個運算元(它們是參考)是否指向記憶體中的同一個物件(幾乎但不完全是指標比較)必然意味著型別是相同的,即使轉換為不同的參考型別: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.因此,更改您的代碼以使用
==.您還可以通過移動
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;
}
}
- 使用
bool(System.Boolean) 值時,您不需要 doif( boolValue == true )或if( !(boolValue == true) )orif( boolValue == false ),您可以執行if( boolValue )andif( !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;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/347442.html
上一篇:盤一盤Java中的abstract和interface(備戰2022春招或暑期實習,每天進步一點點,打卡100天,Day7)
