Heyo, not very familiar with C#, much less Unity, and I'm apparently doing something wrong, here's my code, THe only error I get is:
'Invalid Expression Term "="'
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;
}
}
Any and all help is appreciated!
CodePudding user response:
You're using
===
(I assume from JavaScript?). C# does not have a===
operator, only==
.JavaScript has
===
in order to require that the types of the operands are also strictly the same. C# is statically-typed and most types are not directly comparable so a===
operator isn't necessary.Also, when comparing reference-types (
object
,string
, etc) the==
operator (by default) only checks that both operands (which are references) point to the same single object in memory (almost-but-not-quite a pointer-comparison) which necessarily implies the types are identical, even if cast to different reference-types: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.
So change your code to use
==
.You can also simplify your logic and make your code more readable by moving the
Input.GetKeyDown()
checks and storing that in a localbool isWasd
.
Like so:
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;
}
}
- When working with
bool
(System.Boolean
) values, you don't need doif( boolValue == true )
orif( !(boolValue == true) )
orif( boolValue == false )
, you can doif( boolValue )
andif( !boolValue )
.
Like so:
// 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;
}
}