Search Unity

A namespace cannot directly contain members such as fields or methods?

Discussion in 'Getting Started' started by Taek16, Sep 8, 2019.

  1. Taek16

    Taek16

    Joined:
    Sep 8, 2019
    Posts:
    4
    I have just started using Unity and C#, and I can't find what is causing the error message " A namespace cannot directly contain members such as fields or methods" in my code.
    This is my code:

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

    public class PlayerMovement : MonoBehaviour
    {
    public Rigidbody rb;

    }

    void Update()
    {
    if (Input.GetKey("a"))
    {
    rb.AddForce(-50, 0, 0);
    }

    if (Input.GetKey("d"))
    {
    rb.AddForce(50, 0, 0);
    }
    }
     
  2. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    14,382
    In my experience the most common problems for a beginner are using too many opening/closing braces, mixing up where the braces are positioned, forgetting semi-colons, etc. You have one extra closing brace between the rigidbody declaration and the functions. You need to move it to the bottom of the class below the functions where you're missing a closing brace.
     
    Joe-Censored, Taek16 and JoeStrout like this.
  3. Taek16

    Taek16

    Joined:
    Sep 8, 2019
    Posts:
    4
    This fixed it, thank you so much!