c#特性 在定义时通过反射为gameobject加载资源

在基类中通过反射获取特性

//定义一个特性,path为从resource文件夹加载资源的路径
public class DResource : Attribute
{
    public string path;
    public DResource(string getpath)
    {
        path = getpath;
    }

}

public class ViewBase : MonoBehaviour
{
    protected void Init()
    {
        DResource();
    }
    public void DResource()
    {
        //获取DResource修饰的属性
        var props = this.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
        foreach (var prop in props)
        {
            var attribute = prop.GetCustomAttribute<DResource>();
            if (attribute == null)
            {
                continue;
            }
            string path = attribute.path;
            Debug.Log($"prop{prop.PropertyType}path={path}");
            if (prop.PropertyType==typeof(GameObject))
            {
                var com = Resources.Load(path, prop.PropertyType);
                prop.SetValue(this, com);
            }
            else if (prop.PropertyType == (typeof(Sprite)))
            {

                var sprite = Resources.Load(path, prop.PropertyType) as Sprite;
                prop.SetValue(this, sprite);
            }
            else Debug.Log("无property");
        }
        ////获取DResource修饰的字段
        var fields = this.GetType().GetFields(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
        foreach (var field in fields)
        {
            var attribute = field.GetCustomAttribute<DResource>();
            if (attribute == null)
            {
                continue;
            }
            string path = attribute.path;
            Debug.Log($"fields.{field.FieldType}path={path}");
            if (field.FieldType==typeof(GameObject))
            {
                var com = Resources.Load(path, field.FieldType) as GameObject;
                field.SetValue(this, com);
            }
            else if (field.FieldType==(typeof(Sprite)))
            {
                
                var sprite = Resources.Load(path, field.FieldType) as Sprite;
                field.SetValue(this, sprite);
            }
            else Debug.Log("无field");
        }
    }
}

Test类:

public class Test : ViewBase
{

    [DResource("Prefabs/Item")] private GameObject Item;
    [DResource("Prefabs/Cell")] private GameObject Cell;
    //private ResourceManager resourceManager=ResourceManager.Instance;
    // Start is called before the first frame
    void Awake()
    {
        Init();
    }
    void Start()
    {

        //GameObject Item = Instantiate(resourceManager.GetFirstObjRes("Prefabs/Item") as GameObject);
        GameObject item=Instantiate(Item as GameObject,transform);
        item.transform.SetParent(this.transform);
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容