简体   繁体   中英

Unity error message: A namespace cannot directly contain members such as fields or methods

I am trying to find a movement code for my 2d game and i found this one, but when the scripts compiled it came up with this error message and i don't know what to do. This is the code:

public float moveSpeed = 5;


void Start()
{
   
}


 void Update()
{

    if (Input.GetKey(KeyCode.D))
    {
        transform.position += Vector3.right * moveSpeed * Time.deltaTime;
        
    }
    else if (Input.GetKey(KeyCode.A))
    {
        transform.position += Vector3.right * -moveSpeed * Time.deltaTime;
        
    }

    else if (Input.GetKey(KeyCode.W))
    {
        transform.position += Vector3.up * moveSpeed * Time.deltaTime;

    }
    else if (Input.GetKey(KeyCode.S))
    {
        transform.position += Vector3.up * -moveSpeed * Time.deltaTime;

    }
}

Assuming this is the entirety of your .cs file, the error message would indicate that you're trying to include data or functions outside of a class.

Unlike languages such as C or JS, C# is strictly Object Oriented, so absolutely everything needs to be associated with a class.

Just wrap what you've got in a class and you should be golden. Since you're using Unity, I'd guess you probably want your class to inherit from MonoBehaviour too.

public class MyGameObject: MonoBehaviour
{
    public float moveSpeed = 5;


    void Start()
    {
   
    }


    void Update()
    {

        if (Input.GetKey(KeyCode.D))
        {
            transform.position += Vector3.right * moveSpeed * Time.deltaTime;
        
        }
        else if (Input.GetKey(KeyCode.A))
        {
            transform.position += Vector3.right * -moveSpeed * Time.deltaTime;
        
        }

        else if (Input.GetKey(KeyCode.W))
        {  
            transform.position += Vector3.up * moveSpeed * Time.deltaTime; 

        }
        else if (Input.GetKey(KeyCode.S))
        {
            transform.position += Vector3.up * -moveSpeed * Time.deltaTime;
 
        }
}

There is a much better way to process movement. If you go to project settings > input axes you'll see you dont have to hardcode if statements for each keycode. The 'horizontal' field will have a and leftarrow set for negative(moving left) and d and rightarrow for moving right. Same in the 'vertical' field. Try using this and see how it works:

    void move()
    {
        float moveX = Input.GetAxisRaw("Horizontal");
        float moveY = Input.GetAxisRaw("Vertical");
        moveDirection = new Vector2(moveX, moveY).normalized; 
        rb.velocity = new Vector2(moveDirection.x * moveSpeed, moveDirection.y * moveSpeed);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM