【问题标题】:Attribute is not an attribute class属性不是属性类
【发布时间】:2016-04-16 04:19:20
【问题描述】:

我有以下三个类:

SingletonDrawer.cs:

using UnityEngine;
using UnityEditor;

[CustomPropertyDrawer(typeof(SingletonAttribute))]
public class SingletonDrawer : PropertyDrawer{

    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label){
    }
}

SingletonAttribute.cs:

using UnityEditor;

#if UNITY_EDITOR
[System.SerializableAttribute]
public class SingletonAttribute : PropertyDrawer {
    public System.Type type;
    public SingletonAttribute(System.Type type){
        this.type = type;
    }
}
#endif

TimeTravel.cs:

using UnityEngine;

namespace Simple.TimeTravel {
    [SingletonAttribute(typeof(TimeTravelController))]
    public abstract class TimeTravelController : MonoBehaviour {

    }

}

在我的TimeTravel 类中,我尝试添加SingletonAttribute 属性,但出现以下错误:

'SingletonAttribute' 不是属性类 [Assembly-CSharp] SingletonAttribute.SingletonAttribute(Type type)

我可以做些什么来将该属性附加到一个类?类似于AddComponentMenuDisallowMultipleComponent等...

统一示例 1

DisallowMultipleComponent的Unity示例

[DisallowMultipleComponent]
class MyClass : MonoBehaviour {}

当您尝试将两个相同类型的组件 (MyClass) 添加到 GameObject 时,会打开一个窗口,提示您不能这样做。

Unity 示例 2

RequireComponent的统一示例

[RequireComponent(typeof(Rigidbody))]
class MyClass : MonoBehaviour {}

在此示例中,当您将 MyClass 作为组件添加到游戏对象时,如果 Rigidbody 组件尚未在游戏对象上,则统一将添加该组件。

我想要达到的目标

我想要做的是创建一个名为SingletonSingletonAttribute 的属性,当用户添加具有该属性的组件时,它将查看游戏场景,如果组件已经在场景中,则不添加该组件。

[Singleton(typeof(MyClass))]
class MyClass : MonoBehaviour {}

【问题讨论】:

  • SingletonAttribute 必须扩展 Attribute 才能用作属性。
  • 啊,它扩展了一个系统类,而不是一个统一类......
  • 快速查看documentation 表明SingletonAttribute 可能应该继承自PropertyAttribute
  • @mikez 这样做,给了我这个错误:The attribute 'SingletonAttribute' is not valid on this declaration type. It is valid on 'field' declarations only
  • 好的。我认为你应该更多地解释你试图用团结做什么。我不是统一方面的专家,但您似乎正在尝试使用特定机制,而不仅仅是询问有关如何在 C# 中声明属性的一般性问题。

标签: c# unity3d


【解决方案1】:

您的自定义属性类必须继承自 System.Attribute。

https://msdn.microsoft.com/en-us/library/sw480ze8.aspx

您可以通过定义属性来创建自己的自定义属性 class,直接或间接派生自Attribute的类

【讨论】:

  • 这样做可以消除错误,但在统一内运行OnGUI 不起作用。
猜你喜欢
  • 1970-01-01
  • 2020-06-02
  • 2015-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-12
  • 2014-03-05
  • 2018-08-04
相关资源
最近更新 更多