I’m getting used to C# development on Unity, and I’m coming across an issue that hasn’t happened to me before. It is one single error, only happening on "void Update()". If anyone can help, that would be appreciated!! (Apologies for my poorly written code)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
float horizontalMove = 0f;
public class playermovement : MonoBehaviour {}
public CharacterController2D controller;
public float walkSpeed = 40f;
void Update()
{
horizontalMove = Input.GetAxisRaw("Horizontal") * walkSpeed;
}
void FixedUpdate()
{
controller.Move(horizontalMove * Time.fixedDeltaTime, false, false);
}
Tried getting a 2D Character Movement script to function, as an older one wouldn’t work, ended up with a critical error. Had backups and no corruption, luckily, but still couldn’t resolve on my own.
>Solution :
You are getting the CS8803 error because you have code outside of any namespace or type declaration. In C#, all code must be inside a namespace or type.
The error documentation says:
Top-level statements must precede namespace and type declarations.
To fix this error, you have two options:
- Move the code before the namespace declaration:
float horizontalMove = 0f;
void Update() {
...
}
void FixedUpdate() {
...
}
namespace MyNamespace {
public class PlayerMovement: MonoBehaviour {
...
}
}
- Move the code into a type declaration:
namespace MyNamespace {
public class GlobalCode {
float horizontalMove = 0f;
void Update() {
...
}
void FixedUpdate() {
...
}
}
public class PlayerMovement: MonoBehaviour {
...
}
}
In your case, the best fix would be to move the Update() and FixedUpdate() methods into your PlayerMovement class:
namespace MyNamespace{
public class PlayerMovement : MonoBehaviour {
float horizontalMove = 0f;
void Update() {
...
}
void FixedUpdate() {
...
}
}
}