Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How should I resolve Error: CS8803 on Unity?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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:

  1. Move the code before the namespace declaration:
float horizontalMove = 0f;

void Update() {
    ...
}  

void FixedUpdate() {
   ...    
}

namespace MyNamespace {
    public class PlayerMovement: MonoBehaviour {
        ...
    }
}
  1. 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() {
           ...    
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading