public static string SerliazeRootTask(BehaviorManager.BehaviorTree behaviorTree) { string serializationFilePath = ""; if (null == behaviorTree) { #if UNITY_EDITOR Debug.LogWarning("RootTaskSerializer.SerliazeRootTask ERROR : behaviorTree is NULL"); #endif return(serializationFilePath); } string behaviorTreeName = BehaviorTreeUtility.GetClassNameFromInstance(behaviorTree); string rootTaskName = BehaviorTreeUtility.GetClassNameFromInstance(behaviorTree.rootTask); // 将行为树-根结点键值对存进map BehaviorTreeNamewithRootTaskNameMap.AddPairValue(behaviorTreeName, rootTaskName); // 将map刷新到外存 BTNameAndRTNameDic instance = new BTNameAndRTNameDic(); instance.BTNamRTNameDic = BehaviorTreeNamewithRootTaskNameMap.BTNameMapRTNameDic; ProtoSerializer.SerializeToFile(instance, ProtoSerializer.CONFIG_FILE_NAME); // TODO: 其实序列化的时候不需要泛型,只有反序列化才需要知道 serializationFilePath = ProtoSerializer.SerializeToFile(behaviorTree.rootTask, behaviorTreeName); return(serializationFilePath); }
/// <summary> /// 序列化对象到指定文件内,成功将返回序列化文件路径,失败返回空路径 /// </summary> /// <param name="obj"></param> /// <param name="fileName"></param> /// <returns></returns> public static string SerializeToFile(object obj, string fileName) { string serializationFilePath = ""; if (null == obj) { #if UNITY_EDITOR Debug.LogWarning("ProtoSerializer.Serialize : The object to serialize is NULL"); #endif return serializationFilePath; } // 目录路径 string directoryPath = BehaviorTreeUtility.GetDirectorPathFromCompleteFilePath(fileName); if ("" == directoryPath) { directoryPath = SERIALIZATION_CACHE_DATA_PATH; } else { // 配置文件多一层目录 directoryPath = SERIALIZATION_CACHE_DATA_PATH + directoryPath; } serializationFilePath = SERIALIZATION_CACHE_DATA_PATH + fileName + DATA_POSTFIX; byte[] messageArr; // 获取待序列化对象的类名 string className = BehaviorTreeUtility.GetClassNameFromInstance(obj); // 获取待序列化对象的类型 Type type = BehaviorTreeUtility.GetAssemblyQualifiedType(className); if (false == Directory.Exists(directoryPath)) { try { Directory.CreateDirectory(directoryPath); } catch (System.Exception) { serializationFilePath = ""; #if UNITY_EDITOR Debug.LogWarning("ProtoSerializer.Serialize : Can NOT SaveData because exception is thrown when creating folder!"); #endif } } // try to read the serilization data try { using (FileStream fileStream = File.Create(serializationFilePath)) { using (MemoryStream messageStream = new MemoryStream()) { // 由于泛型未知,只能根据Type实例来调用ProtoBuf的Serlizer类的泛型函数Serialize BehaviorTreeUtility.CallGenericFunctionByType(typeof(Serializer), "Serialize", new object[] { messageStream, obj }, type); messageArr = messageStream.ToArray(); fileStream.Write(messageArr, 0, messageArr.Length); fileStream.Close(); } } } catch (System.Exception) { #if UNITY_EDITOR #if UNITY_EDITOR Debug.LogWarning("ProtoSerializer.Serialize : Can NOT SaveData " + serializationFilePath + #endif ", because exception is thrown when creating the file."); #endif serializationFilePath = ""; } return serializationFilePath; }