【问题标题】:Unable to extend MonoBehaviour class, "The name does not exist in the current context" Error无法扩展 MonoBehaviour 类,“当前上下文中不存在该名称”错误
【发布时间】:2019-08-03 16:30:50
【问题描述】:

我有一个继承 MonoBehaviour 的类。 GameObject 的扩展方法有效,但 MonoBehaviour 无效。

类文件

namespace UnityEngine
{
    public class Test : MonoBehaviour
    {
        private void Start()
        {
            TestMono();
            gameObject.TestObject();
        }
    }
}

扩展文件

namespace UnityEngine
{
    public static class MonoBehaviourExt
    {
        public static void TestObject(this GameObject obj) {}
        public static void TestMono(this MonoBehaviour obj) {}
    }
}

在 Start() 方法中,TestMono() 方法带有红线下划线,错误为“当前上下文中不存在名称 'TestMono'。”。

据我了解,在 C# 中无法阻止类扩展,而且我看不到我的错误在哪里。

【问题讨论】:

  • 很奇怪,但试试 this.TestMono
  • this.TestMono 有效!您可以将其发布为答案吗?我想知道为什么没有这个就不行。
  • 顺便说一句,不要使用namespace UnityEngine。如果您要使用命名空间,请使用您自己的命名空间。
  • 是的,我将其发布为答案

标签: c# unity3d extension-methods


【解决方案1】:

您应该使用this.TestMono() 使其工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多