在基类中通过反射获取特性
//定义一个特性,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);
}