首页 > 解决方案 > 接收关于统一的 } 预期和命名空间问题

问题描述

在统一上制作 2D 平台游戏,我继续收到以下两个错误,这是 C# 的新手,不确定为什么会发生这种情况。

“Assets\PlayerController.cs(15,41): 错误 CS1513: } 预期”

“Assets\PlayerController.cs(70,1):错误 CS1022:类型或命名空间定义,或预期文件结尾”

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

public class PlayerController : MonoBehaviour 
{
    private Rigidbody2D rb;
    
    [SerializeField] private Animator anim;


    private void Start()
    {
        rb = GetComponent<Rigidbody2D>(); 
        anim = GetComponent<Animator>(); 
        private enum State {idle, running, jumping}
        private State state = State.idle;
    }



    private void Update() 
    {
        float hdirection = Input.GetAxis("Horizontal");
        float vdirection = Input.GetAxis("Vertical");

        if (hdirection < 0)
        {
            rb.velocity = new Vector2(-7, rb.velocity.y);
            gameObject.GetComponent<SpriteRenderer>().flipX = true;
        }    
        else if (hdirection > 0)
        {
            rb.velocity = new Vector2(7, rb.velocity.y);
            gameObject.GetComponent<SpriteRenderer>().flipX = false; 
        }

        else
        {
            
        }

        if (Input.GetKeyDown(KeyCode.Space))
        {
            rb.velocity = new Vector2(rb.velocity.x, 12);
            state = State.jumping;
        }

        VelocityState();
    }

    private void VelocityState()
    {
        if(state == State.jumping)
        {

        }

        else if(Mathf.Abs(rb.velocity.x > Mathf.Epsilon))
        {
            state = State.running;
        }

        else 
        {
            state = State.idle; 
        }
    }

}
    

标签: c#unity3d

解决方案


您不能在函数中定义私有变量。枚举和变量状态应该在外面定义。

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

public class PlayerController : MonoBehaviour
{
private Rigidbody2D rb;

[SerializeField] private Animator anim;

private enum State { idle, running, jumping };
private State state;

private void Start()
{
    rb = GetComponent<Rigidbody2D>();
    anim = GetComponent<Animator>();
    state = State.idle;
}
private void Update()
{
    float hdirection = Input.GetAxis("Horizontal");
    float vdirection = Input.GetAxis("Vertical");

    if (hdirection < 0)
    {
        rb.velocity = new Vector2(-7, rb.velocity.y);
        gameObject.GetComponent<SpriteRenderer>().flipX = true;
    }
    else if (hdirection > 0)
    {
        rb.velocity = new Vector2(7, rb.velocity.y);
        gameObject.GetComponent<SpriteRenderer>().flipX = false;
    }

    else
    {

    }

    if (Input.GetKeyDown(KeyCode.Space))
    {
        rb.velocity = new Vector2(rb.velocity.x, 12);
        state = State.jumping;
    }

    VelocityState();
}

private void VelocityState()
{
    if (state == State.jumping)
    {

    }

    else if (Mathf.Abs(rb.velocity.x) > Mathf.Epsilon)
    {
        state = State.running;
    }

    else
    {
        state = State.idle;
    }
}

}


推荐阅读