本来我是以为泛型 ScriptableObject 是不可能的
但是我之前在制作技能条件时的尝试让我感觉到一个可能性
当时我是做成这样子的
其实这已经很好看了
当时我是实现了获取一个已知物体的所有字段,然后把字段名显示出来,还处理了字段信息不能序列化的问题
这给了灵感就是,我为什么不直接把我要用到的类型信息先定义好,就是说,放到一个静态类里面,然后在我需要的时候直接用呢?这不就是 Bolt,FlowCanvas 里面要先定义变量类型的原因吗
那么其实我就是要根据一个类型来创造一个实例
这让我想到了之前在 GF 里面看到的一个创建实例的函数 Activator.CreateInstance
我当时看到的时候我就去搜了,然后不知道那个是用来干嘛的
现在实际用了一遍反射才知道,根据 type 直接就能创建了……强啊
Activator.CreateInstance
试验
// ----------------------------------------------
// 作者: 廉价喵
// 创建于: 31/03/2022 23:20
// 最后一次修改于: 01/04/2022 0:28
// 版权所有: CheapMeowStudio
// 描述:
// ----------------------------------------------
using System;
using System.Reflection;
using Sirenix.OdinInspector;
using UnityEngine;
namespace MeowACT
{
public class testMono : SerializedMonoBehaviour
{
public void Awake()
{
Type t = typeof(int);
var obj = Activator.CreateInstance(t);
Debug.Log(obj);
}
}
}
Debug 可以输出 0
那这就起飞了啊
首先定义所有要用到的类型
// ----------------------------------------------
// 作者: 廉价喵
// 创建于: 01/04/2022 0:15
// 最后一次修改于: 01/04/2022 0:35
// 版权所有: CheapMeowStudio
// 描述:
// ----------------------------------------------
using System;
using System.Collections.Generic;
using UnityEngine;
namespace MeowACT
{
/// <summary>
/// 可资产化变量的类型
/// </summary>
public static class ScriptableVariableType
{
/// <summary>
/// 可资产化变量的类型列表
/// </summary>
public static List<Type> TypeList = new List<Type>
{
typeof(int),
typeof(float),
typeof(string),
typeof(bool),
typeof(Vector2),
typeof(Vector3),
typeof(Quaternion)
};
}
}
然后定义根据类型列表获得类型名称列表的函数
// ----------------------------------------------
// 作者: 廉价喵
// 创建于: 30/03/2022 21:57
// 最后一次修改于: 01/04/2022 0:49
// 版权所有: CheapMeowStudio
// 描述:
// ----------------------------------------------
using System;
using System.Collections.Generic;
using System.Reflection;
using Sirenix.OdinInspector;
namespace MeowACT
{
public static class AttributeUtility
{
/// <summary>
/// 根据类型列表获得类型名称列表
/// </summary>
/// <param name="typeList">类型列表</param>
/// <returns></returns>
public static IList<ValueDropdownItem<string>> GetTypeNameList(List<Type> typeList)
{
ValueDropdownList<string> valueDropdownItems = new ValueDropdownList<string>();
foreach (var type in typeList)
{
valueDropdownItems.Add(type.Name);
}
return valueDropdownItems;
}
/// <summary>
/// 根据类型名称在类型列表中找到类型
/// </summary>
/// <param name="typeList">类型列表</param>
/// <param name="typeName">待查找类型名称</param>
/// <returns></returns>
public static Type GetTypeInTypeList(List<Type> typeList, string typeName)
{
foreach (var type in typeList)
{
if (type.Name == typeName)
return type;
}
return null;
}
}
}
然后这是一个希望有通用性的可资产化变量
// ----------------------------------------------
// 作者: 廉价喵
// 创建于: 01/04/2022 0:40
// 最后一次修改于: 01/04/2022 0:54
// 版权所有: CheapMeowStudio
// 描述:
// ----------------------------------------------
using System;
using System.Collections.Generic