Search Unity

Question How do I fix error CS8803 (game cameras)

Discussion in 'Getting Started' started by unity_A6EC1A68F09DDA9C2430, Feb 15, 2024.

  1. unity_A6EC1A68F09DDA9C2430

    unity_A6EC1A68F09DDA9C2430

    Joined:
    Feb 1, 2024
    Posts:
    3
    I was coding game cameras in a tutorial but I got error CS8803 (Top-level statements must precede namespace and type declarations). Here is the code:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class GameController : MonoBehaviour {
    6.  
    7.     public GameObject[] gameCameras;
    8.  
    9.     private int gameCameraIndex = 0;
    10.  
    11.     // Start is called before the first frame update
    12.     void Start() {
    13.         FocusOnCamera (gameCameraIndex);
    14.     }
    15.  
    16.     // Update is called once per frame
    17.     void Update() {
    18.      if (Input.GetMouseButtonDown(0)) {
    19.             ChangeCamera (1);
    20.         }
    21.     }
    22.  
    23.     void FocusOnCamera (int index) {
    24.         for (int i = 0; i < gameCameras.Length; i++) {
    25.             gameCameras [i].SetActive (i == index);
    26.         }
    27.     }
    28. }
    29.  
    30. void ChangeCamera (int direction) {
    31.     gameCameraIndex += direction;
    32.  
    33.     if (gameCameraIndex >= gameCameras.Length) {
    34.         gameCameraIndex = 0;
    35.     }
    36.  
    37.     if (gameCameraIndex <= 0) {
    38.         gameCameraIndex = gameCameras.Length - 1;
    39.     }
    40.  
    41.     FocusOnCamera (gameCameraIndex);
    42. }
    43.  
    How do i fix this?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,725
    You're just making typing mistakes.

    You can fix all your own typing mistakes with the help of the errors.

    Go look where you go this. You haven't copied it correctly. You have put some of your code outside of your class.

    As C# specifies, 100% of all code must be within a class.

    Two steps to tutorials:

    1. do them perfectly, to the letter (zero typos, including punctuation and capitalization)
    2. stop and understand each step what is going on, otherwise you're just wasting time.
     
  3. BABIA_GameStudio

    BABIA_GameStudio

    Joined:
    Mar 31, 2020
    Posts:
    497
    If you just check through your brackets { and } you should be able to see that you closed your class on line 28 but then have a method
    ChangeCamera
    afterwards. This method needs to be inside your class, so just move it so that it is.