Hello everyone, I’m trying to make a top down game/game prototype and I’ve just began with scripting. So I’ve seen some 2D top down tutorials and took the D movement of a tutorial trying to replicate it with W but when I save my script and try to play it, it says “Parsing Error”. I suppose it means that I need to use this symbol “{}” in some way but I don’t understand the symbol at all.
I see these “{}” symbols in every script but I don’t understand how they work, what they do or even when to use them.
My script:
using UnityEngine;
using System.Collections;
public class PlayerMobility : MonoBehaviour {
public float speed;
void Update () {
if (Input.GetKey (KeyCode.D))
//transform.Translate (Vector2.right * speed);
//transform.position += Vector3.right * speed;
if (Input.GetKey (KeyCode.W))
//transform.Translate (Vector2.up * speed);
//transform.position += Vector3.up * speed;
Simplified, they define scopes. Think of them as “from here” and “to here” markers.
public class MyClass
{ // MyClass body starts here
public void MyMethod()
{ // MyMethod body starts here
if (true)
{ // statement block starts here
// Code...
// Code...
// Code...
} // statement block ends here
} // MyMethod body ends here
} // MyClass body ends here
C# Language Specification (.NET 2003 docs, so somewhat old but still relevant)
Your code is missing the body terminator for your class and method, and you want to create a statement block after you if, because you have more than one statement.
using UnityEngine;
using System.Collections;
public class PlayerMobility : MonoBehaviour
{
public float speed;
void Update()
{
// After if (expression) follows a statement, or a statement block
if (Input.GetKey(KeyCode.D))
// Statement "block", containing multiple statements
{
transform.Translate(Vector2.right * speed); // One statement
transform.position += Vector3.right * speed; // Another statement
}
if (Input.GetKey(KeyCode.W))
{
transform.Translate(Vector2.up * speed);
transform.position += Vector3.up * speed;
}
}
}
Since your code appear to do the same thing twice, we can get rid of one statement in each block and thus simplify the code by removing the block entirely.
using UnityEngine;
using System.Collections;
public class PlayerMobility : MonoBehaviour
{
public float speed;
void Update()
{
// After if (expression) follows a statement, or a statement block
if (Input.GetKey(KeyCode.D))
transform.Translate(Vector2.right * speed); // One statement
if (Input.GetKey(KeyCode.W))
transform.Translate(Vector2.up * speed);
}
}