Search code examples
c#unity-game-enginebuttonmenukeycode

"error CS0116: A namespace cannot directly contain members such as fields or methods" in Unity


I am working on a game in unity and in the script for controlling the buttons in the game mode menu. While writing this error occurred: error CS0116: A namespace cannot directly contain members such as fields or methods and i have no idea whats wrong. Heres the code:

using System.Collections.Generic;
using UnityEngine;

public class SecondaryMenuControl : MonoBehaviour
{

public bool isSurvival;  
public bool isSelectLevel;
public bool isGoBack;


} 

 // Start is called before the first frame update
    void Start()
    {

void OnMouseUp(){
    if(isSurvival)
    {
        SceneManager.LoadScene(MainScene);
    }

    if (isSurvival)
    {
        SceneManager.LoadScene(SelectLevelMenu);
    }

    if (isGoBack)
    {
        SceneManager.LoadScene(IntroMenu);  
    }

    }

    // Update is called once per frame
    void Update()
    {

    }
}

I hope somebody can help me.

Regards, Keno


Solution

  • Remove the stray bracket;

    public class SecondaryMenuControl : MonoBehaviour
    {
    
    public bool isSurvival;  
    public bool isSelectLevel;
    public bool isGoBack;
    
    
    } // remove this one!
    
    // rest of the file
    
    

    The error basically saids 'You defined some properties/fields/methods in a namespace' which you of course can't do. They all belong inside a class.

    edit: this should be your output:

    public class SecondaryMenuControl : MonoBehaviour
    {
    
    public bool isSurvival;  
    public bool isSelectLevel;
    public bool isGoBack;
    
    private void OnMouseUp(){
        if(isSurvival)
        {
            SceneManager.LoadScene(MainScene);
        }
    
        if (isSurvival)
        {
            SceneManager.LoadScene(SelectLevelMenu);
        }
    
        if (isGoBack)
        {
            SceneManager.LoadScene(IntroMenu);  
        }
    
    } // end of OnMouseUp
    } // end of class
    

    make sure you match an opening bracket with a closing one.