You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity编写敌人AI时遇CS0116错误:命名空间不能直接包含成员

问题排查与解决

CS0116错误的核心原因是**OnDrawGizmosSelected()方法定义在了EnemyController类的外部**,C#语法规定,所有字段、方法等成员必须包含在类或结构体的内部,不能直接暴露在命名空间层级下。

你的代码中,EnemyController类的闭合大括号}在第21行,而OnDrawGizmosSelected()方法写在了这个大括号之后,导致该方法不属于任何类,触发了命名空间不能直接包含成员的错误。

修正后的代码

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

public class EnemyController : MonoBehaviour
{
    public float lookRadius = 10f;

    // Start is called before the first frame update
    void Start()
    {
        
    }

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

    void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawWireSphere(transform.position, lookRadius);
    }
}

只需将OnDrawGizmosSelected()方法移动到EnemyController类的内部(即类的闭合大括号之前),错误即可解决。

内容的提问来源于stack exchange,提问作者Indigo Wolf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 20:05:17