Top-level statements must precede namespace and type declarations, on line 22, it says i cant use methods in a variable how else could i name the variable?

JD Harris 0 Reputation points
2025-10-23T05:28:13.25+00:00
using UnityEngine;

public class NewMonoBehaviourScript : MonoBehaviour

{
    // Variables
    public float speed = 5.0f;
    public float turnspeed;


    

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {

    }
    }

    // Update is called once per frame
    void Update()
{
    public float horizontalInput;
    public float forwardInput;

    //Get the horizontal input
         horizontalInput = Input.GetAxis("Horizontal");
         forwardInput = Input.GetAxis("Vertical");
         
        //Move the vehicle forward continuously
        transform.Translate(Vector3.forward * Time.deltaTime * speed * forwardInput);
        transform.Translate(Vector3.right * Time.deltaTime * turnspeed * horizontalInput);
    }


Windows development | Windows App SDK
{count} votes

1 answer

Sort by: Most helpful
  1. Raymond Huynh (WICLOUD CORPORATION) 3,645 Reputation points Microsoft External Staff Moderator
    2025-10-23T07:11:26.1033333+00:00

    Hello JD Harris ,
    The issue is that you're using public inside the Update method. You can't do that in C#.
    You should move "public float horizontalInput" and "public float forwardInput" to the same level as "public float turnspeed" (Class level).

    Variables declared inside methods can't have public/private.
    Hope this helps!


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.