A namespace cannot directly contain members such as fields or methods

The title is the error im getting can some one help me fix it?
my code is:

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

public class PlayerMovement : MonoBehaviour
{
    public float turnSpeed = 4.0f;
    public float moveSpeed = 2.0f;

    public float minTurnAngle = -90.0f;
    public float maxTurnAngle = 90.0f;
    private float rotX;
    // Start is called before the first frame update
    void Start()
    {
      
    }

    // Update is called once per frame
    void Update()
    {
        MouseAiming();
        KeyboardMovement();
        if (Input.GetMouseButtonDown(0))
        {
            GetComponent<Light>().enabled = !GetComponent<Light>().enabled;
        }

    }
}
void MouseAiming()
{
    // get the mouse inputs
    float y = Input.GetAxis("Mouse X") * turnSpeed;
    rotX += Input.GetAxis("Mouse Y") * turnSpeed;

    // clamp the vertical rotation
    rotX = Mathf.Clamp(rotX, minTurnAngle, maxTurnAngle);

    // rotate the camera
    transform.eulerAngles = new Vector3(-rotX, transform.eulerAngles.y + y, 0);
}

void KeyboardMovement()
{
    Vector3 dir = new Vector3(0, 0, 0);

    dir.x = Input.GetAxis("Horizontal");
    dir.z = Input.GetAxis("Vertical");

    transform.Translate(dir * moveSpeed * Time.deltaTime);
}

Line 30 in your code. That’s the closing curly brace for the class. Move it to line 53.

1 Like

Help. Im making a gun shoot but i keep getting this error on the “Update” bit and that “GetComponent” doesn’t exist in current context

using UnityEngine;

private void Update()
{
    if (Input.GetButtonDown("Fire1"))
    {
        AudioSource gunsound = GetComponent<AudioSource>();
        gunsound.Play();
        GetComponent<Animation>().Play("Gunshot");
    }
}

Does the object the script is attached to have an AudioSource and Animation Component?

As the error says, your code has to live inside a class. Update() method in this code you shared is just floating inside nothing. Create a new script in Unity and look at the template it creates. Model your script after that.

2 Likes

Yes it is

Ohh ok thanks!