C# 像unity这样的复合属性?

C# 像unity这样的复合属性?,c#,unity3d,attributes,game-engine,C#,Unity3d,Attributes,Game Engine,我目前正在使用GDI+开发一个基于组件的C#游戏引擎,并且已经到了一些组件依赖其他组件的地步 我希望创建一个RequiremoComponents属性,它检查游戏对象是否包含所需的组件(很像unity如何做) 我以前从未真正创建过自定义属性。。。很抱歉,如果我听起来很蠢,但我不知道该怎么做 这就是我到目前为止所拥有的一切哈哈: using System; using System.Collections.Generic; using System.Linq; using System.Text;

我目前正在使用GDI+开发一个基于组件的C#游戏引擎,并且已经到了一些组件依赖其他组件的地步

我希望创建一个RequiremoComponents属性,它检查游戏对象是否包含所需的组件(很像unity如何做)

我以前从未真正创建过自定义属性。。。很抱歉,如果我听起来很蠢,但我不知道该怎么做

这就是我到目前为止所拥有的一切哈哈:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GameEngine.Components
{
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
    public class RequireComponent : Attribute
    {
        public RequireComponent(Type type)
        {

        }
    }
}

任何帮助都将不胜感激。

其余部分完全取决于您的库,但我认为这几乎就是您在属性级别所需的全部内容

只需添加一个字段来存储所需的类型,以便以后使用

Type componentType;
public Type ComponentType{
  get{ return componentType; }
}
在构造函数中设置它

稍后,将组件添加到实体时

// Returns whether the component is successfully added
public bool AddComponent(Component c){
  var attribute = 
    c.GetType().
    GetCustomAttributes(typeof(RequireComponent), true).
    FirstOrDefault() as RequireComponent;
  if (attribute != null)
  {
    // Check requirements
    if(!AlreadyHasComponent(requiredAttribute.ComponentType)){
      return false;
    }
  }
  // Requirements met: Add c
  return true;
}
您可能希望将该字段改为
列表

甚至可以查看一下现有的统一ECS库。
有一个我特别尝试过并且非常喜欢的方法:

RequiredComponent属性缺少什么,您需要创建自己的属性?