Search code examples
c#unity-game-enginecurly-braces

Curly brackets won't Bracket properly


Every time I write this code the brackets decide to link to a different bracket and if I rewrite the code it'll work properly until I save and close the file then open it where the same problem happens. I use Visual Studio 2022

I have tried deleting all the {}s and replacing them and it doesn't work, same with copying the code and pasting it back

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RunState : MovementBaseState

{
    public override void EnterState(MovementStateManager movement);
    {
    movement.anim.SetBool("Running", true)
    }

    public override void UpdateState(MovementStateManager movement);
    {
    if (movement.dir.magnitude < 0.1f) ExitState(movement, movement.Idle);
    }


    void ExitState(MovementStateManager movement, MovementBaseState state);
    {
    movement.anim.SetBool("Running", false);
    movement.SwitchState(state);
    }
}

The brackets linking to the wrong bracket


Solution

  • Your semi-colons are on the wrong lines. They are statement terminators, not end of line markers.

    public override void EnterState(MovementStateManager movement);
    {
    movement.anim.SetBool("Running", true)
    }
    

    should be:

    public override void EnterState(MovementStateManager movement)
    {
        movement.anim.SetBool("Running", true);
    }
    

    You should be able to fix up the rest. Things like if statements should not have a semi-colon at the end if there are braces or a new-line to a single statement, basically anything where you would use {} braces should not have a semi-colon before the braces. The braces are optional for single-line conditional statements so the following are equivalent:

    if (movement.dir.magnitude < 0.1f) ExitState(movement, movement.Idle);
    
    if (movement.dir.magnitude < 0.1f) 
        ExitState(movement, movement.Idle);
    
    if (movement.dir.magnitude < 0.1f) 
    {
        ExitState(movement, movement.Idle);   
    }
    

    The semi-colon works on the first line because it terminates the statement "ExitState(movement, movement.Idle);"