【发布时间】: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)
我可以做些什么来将该属性附加到一个类?类似于AddComponentMenu、DisallowMultipleComponent等...
统一示例 1
DisallowMultipleComponent的Unity示例
[DisallowMultipleComponent]
class MyClass : MonoBehaviour {}
当您尝试将两个相同类型的组件 (MyClass) 添加到 GameObject 时,会打开一个窗口,提示您不能这样做。
Unity 示例 2
RequireComponent的统一示例
[RequireComponent(typeof(Rigidbody))]
class MyClass : MonoBehaviour {}
在此示例中,当您将 MyClass 作为组件添加到游戏对象时,如果 Rigidbody 组件尚未在游戏对象上,则统一将添加该组件。
我想要达到的目标
我想要做的是创建一个名为Singleton 或SingletonAttribute 的属性,当用户添加具有该属性的组件时,它将查看游戏场景,如果组件已经在场景中,则不添加该组件。
[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# 中声明属性的一般性问题。