从父类数组中 放入 不同的 子类.asset或者实体,并且 通过 父类数组 获得 不同 子类 的变量。
方法1:
基类用virtual方法,继承的子类用override方法获得变量的值。(计算简单,调用少量变量的时候 快捷)
方法2:
FieldInfo[] fil = type.GetFields();
(遍历每一个 子类 的变量,包括继承 父类 的变量,对于 大量 重复 调用 的变量 效果拔群)
应用:不同物品、食物:物品、装备:物品。
建筑、商店:建筑、可破坏建筑:建筑、不可破坏建筑:建筑。
逻辑图。
TestFather.cs
using UnityEngine;
//.cs脚本 继承ScriptableObject,才能使得 CreateAssetMenu 生效
[CreateAssetMenu(fileName = "New TestFather", menuName = "TestFather")]
public class TestFather : ScriptableObject {
public int int_a = 1;
public int int_b = 2;
public virtual TestStyle testStyle_()
{
return TestStyle.AA;
}
}
创建一个 TestSone_1.asset,使得其变量testStyle为 非AA,可以为BB、CC、DD,用于区分。
TestSon_1.cs
using UnityEngine;
[CreateAssetMenu(fileName = "New TestSon", menuName = "TestSon_1")]
public class TestSon_1 : TestFather
{
public int a_1 = 101;
public int b_2 = 102;
public TestStyle testStyle;
public override TestStyle testStyle_()
{
return testStyle;
}
}
public enum TestStyle
{
AA,
BB,
CC,
DD,
}
TestSon_2.cs
using UnityEngine;
[CreateAssetMenu(fileName = "New TestSon", menuName = "TestSon_2")]
public class TestSon_2 : TestFather
{
public int a_1 = 101;
public int b_2 = 102;
public override TestStyle testStyle_()
{
return TestStyle.AA;
}
}
TestArray.cs
using UnityEngine;
using System;
using System.Reflection;//FieldInfo
public class TestArray : MonoBehaviour
{
public TestFather[] fatherArray;//这个数组里面可以存放TestSon_1.asset和TestSon_2.asset
public TestFather father_;//可以用TestSon_1.asset或者TestSon_2.asset来单个测试
private void Start()
{
Debug.Log(" ");
if (father_ != null
&& fatherArray.Length > 0
&& father_.GetType().ToString() == "TestSon_1")
{
Type type = father_.GetType();
TestSon_1 someInstance = ScriptableObject.CreateInstance(type.ToString()) as TestSon_1;//这里创建的someInstace 是一个 成员未赋值的 子类
//someInstance = type;//无法转换
Debug.Log(" someInstance.testStyle.ToString():" + someInstance.testStyle.ToString());
Debug.Log(" ");
Debug.Log(" father_.testStyle_():" + father_.testStyle_()); //如果测试的 是TestSon_1.asset,则这里会显示 BB或者CC或者DD
Debug.Log(" ");
Debug.Log(" 显示子类继承父类 的 变量的值-----------------------");
FieldInfo[] fil = type.GetFields();//using System.Reflection;
foreach (FieldInfo var in fil)//仅能获取到c字段(输出c=2)
{
Debug.Log("FieldInfo: " + var.Name + "=" + var.GetValue(father_));
if (var.GetType().ToString() == "TestStyle")//找到 TestSon_1.asset中的 TestStyle类型名字为testStyle的变量
{
Debug.Log("TestStyle:"+ var.GetValue(father_));
}
}
}
}
}
参考资料:
1.C# Object.GetType()获取对象的类类型/获取类的类型
2.ScriptableObject.CreateInstance<MyScriptableObject >();
【Unity】ScriptableObject的介绍
3.
PropertyInfo、FieldInfo、MemberInfo的区别
4.