【问题标题】:Unity C# error 'cs0116' "A namespace cannot directly contain members such as fields or methods" [closed]Unity C#错误'cs0116'“命名空间不能直接包含字段或方法等成员”[关闭]
【发布时间】:2020-12-15 08:52:15
【问题描述】:

我在 C# 脚本和整个 Unity 方面还是个新手。

我已经看过教程并阅读了十几个论坛中出现相同错误的用户,我已经尝试修复它 但我觉得我把事情搞砸了。

Unity 说错误在第 16 行第 10 列,视觉研究无法发现任何错误。 它本来是一个简单的脚本,可以让我的角色移动,但要解决正在发生的事情变得非常困难。

Unity 在说什么:

https://ibb.co/sbF2SPK

我的脚本:

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

public class NewBehaviourScript : MonoBehaviour
{
    // Start is called before the first frame update
    void Start(int mDir)
    { }
    private float speed = 2.0f;
    public GameObject character;
}


    // Update is called once per frame
    void Update()
{

    if (Input.GetKey(KeyCode.D))
    {
        transform.position += Vector3.right * speed * Time.deltaTime;
    }
    if (Input.GetKey(KeyCode.A))
    {
        transform.position += Vector3.left * speed * Time.deltaTime;
    }
    if (Input.GetKey(KeyCode.W))
    {
        transform.position += Vector3.up * speed * Time.deltaTime;
    }
    forward;
    if (Input.GetKey(KeyCode.S))
    {
        transform.position += Vector3.down * speed * Time.deltaTime;
    }
}

【问题讨论】:

标签: c# unity3d


【解决方案1】:

所有成员(字段、属性和方法)都必须在一个类中。在您的情况下,方法 Update 不在类中。也许您过早关闭课程NewBehaviourScript。更多信息在the official documentation

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

namespace MyProject
{
    public class NewBehaviourScript : MonoBehaviour
    {
        // Start is called before the first frame update
        void Start(int mDir)
        {
        }

        private float speed = 2.0f;
        public GameObject character;

        // Update is called once per frame
        void Update()
        {
            if (Input.GetKey(KeyCode.D))
            {
                transform.position += Vector3.right * speed * Time.deltaTime;
            }
            if (Input.GetKey(KeyCode.A))
            {
                transform.position += Vector3.left * speed * Time.deltaTime;
            }
            if (Input.GetKey(KeyCode.W))
            {
                transform.position += Vector3.up * speed * Time.deltaTime;
            }
            forward;
            if (Input.GetKey(KeyCode.S))
            {
                transform.position += Vector3.down * speed * Time.deltaTime;
            }
        }
    } // Close the class NewBehaviourScript
} // Close the namespace

小建议,你也可以将类封装在命名空间分类类中。一般命名空间名称为项目名称+文件夹结构。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多