/// <summary> /// 读取JSon文件信息 /// </summary> /// <typeparam name="T">需要输出的类型</typeparam> /// <param name="data">输入指定的参数</param> public T Read <T>(string path) { ConfigPath = path; if (!File.Exists(ConfigPath)) { LogTool.LogError(string.Format("并未读取到{0}路径", ConfigPath)); return(default(T)); } using (StreamReader sr = new StreamReader(ConfigPath)) { string json = sr.ReadToEnd(); if (json.Length > 0) { if (jSonUtilType == JSonUtilType.JsonUtility) { return(JsonUtility.FromJson <T>(json)); } else { return(JsonConvert.DeserializeObject <T>(json)); } } } return(default(T)); }
/// <summary> /// 直接修改数值 /// </summary> /// <param name="dic"></param> /// <param name="key"></param> /// <param name="value"></param> /// <typeparam name="Tkey"></typeparam> /// <typeparam name="TValue"></typeparam> /// <returns></returns> public static TValue SetDictionaryValue <Tkey, TValue>(this Dictionary <Tkey, TValue> dic, Tkey key, TValue value) { if (!dic.ContainsKey(key)) { LogTool.LogError($"没有Key对应的Value", LogEnum.NormalLog); } dic[key] = value; return(dic[key]); }
/// <summary> /// 获取字典值 /// </summary> /// <param name="dic"></param> /// <param name="key"></param> /// <typeparam name="Tkey"></typeparam> /// <typeparam name="TValue"></typeparam> /// <returns></returns> public static TValue GetDictionaryValue <Tkey, TValue>(this Dictionary <Tkey, TValue> dic, Tkey key) { dic.TryGetValue(key, out TValue value); if (value == null) { LogTool.LogError($"没有Key对应的Value", LogEnum.NormalLog); } return(value != null ? value : default(TValue)); }
/// <summary> /// 获取SortList值 /// 根据string转换成enum来处理 /// </summary> /// <param name="sortList"></param> /// <param name="key"></param> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TValue"></typeparam> /// <returns></returns> public static TValue GetSortListValue <TKey, TValue>(this SortedList <TKey, TValue> sortList, string key) { sortList.TryGetValue((TKey)Enum.Parse(typeof(TKey), key), out TValue value); if (value == null) { LogTool.LogError($"没有Key对应的Value", LogEnum.NormalLog); } return(value != null ? value : default(TValue)); }
public override void SetCurrActivity(StateTag tag) { if (!StateSortList.ContainsKey(tag)) { LogTool.LogError($"未发现注册 {tag} 标签"); return; } currStateTag = tag; currState = stateSortList[tag]; }
/// <summary> /// 移除相对应的Key /// </summary> /// <param name="dic"></param> /// <param name="key"></param> /// <typeparam name="Tkey"></typeparam> /// <typeparam name="TValue"></typeparam> /// <returns></returns> public static bool RemoveDictionaryElements <Tkey, TValue>(this Dictionary <Tkey, TValue> dic, Tkey key) { if (dic.ContainsKey(key)) { dic.Remove(key); return(true); } else { LogTool.LogError($"不含有相对应的 Key: {key}"); return(false); } }
/// <summary> /// 移除相对应的Key /// </summary> /// <param name="sortList"></param> /// <param name="key"></param> /// <typeparam name="Tkey"></typeparam> /// <typeparam name="TValue"></typeparam> /// <returns></returns> public static bool RemoveSortListElements <Tkey, TValue>(this SortedList <Tkey, TValue> sortList, Tkey key) { if (sortList.ContainsKey(key)) { sortList.Remove(key); return(true); } else { LogTool.LogError($"不含有相对应的 Key: {key}"); return(false); } }
/// <summary> /// 设置一个相对的数值 /// </summary> /// <param name="tag"></param> /// <param name="value"></param> public void SetParameter(ParameterTag tag, int value) { var unit = ParameterList.GetSortListValue(tag); if (unit != null) { unit.Value += value; if (unit.Value < unit.DynamicRange.x) { unit.Value = unit.DynamicRange.x; } else if (unit.Value > unit.DynamicRange.y) { unit.Value = unit.DynamicRange.y; } } else { LogTool.LogError("未发现对应标签!!!"); } RefreshPanelInfo(); }
protected override IEnumerator Task() { LogTool.Log($"{TaskName.Value}", LogEnum.TaskLog); yield return(new WaitForFixedUpdate()); var memory = 0L; #if UNITY_EDITOR || UNITY_STANDALONE try { var MemInfo = new MemoryInfo(); GlobalMemoryStatus(ref MemInfo); memory = Convert.ToInt64(MemInfo.AvailPhys.ToString()) / 1024 / 1024; LogTool.Log($"FreeMemory: {Convert.ToString(memory)} MB", LogEnum.TaskLog); if (memory < memoryDefault) { LogTool.LogError($"内存不足!", LogEnum.TaskLog); //弹出内存警告 } else { LogTool.Log($"可以使用 ^_^", LogEnum.TaskLog); //自动取消内存警告 LogTool.Log($"{Environment.WorkingSet.ToString()}", LogEnum.TaskLog); } } catch (Exception e) { Console.WriteLine(e); throw; } #elif UNITY_ANDROID // try // { // AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); // AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity"); // AndroidJavaClass unityPluginLoader = new AndroidJavaClass("java类全名"); // float tempMemory = unityPluginLoader.CallStatic<float>("GetMemory", currentActivity); // memory = (int) tempMemory; // if (memory < memoryDefault) // { // LogUtil.LogError(string.Format("内存不足!"), LogType.TaskLog); // //弹出内存警告 // } // else // { // LogUtil.Log(string.Format("可以使用 ^_^"), LogType.TaskLog); // //自动取消内存警告 // LogUtil.Log(Environment.WorkingSet.ToString(), LogType.TaskLog); // } // } // catch (Exception e) // { // Console.WriteLine("com.moba.unityplugin.AndroidUtile GetMemory: " + e.Message); // throw; // } #elif UNITY_IOS try { //TODO 不知道怎么做 // task_basic_info_data_t taskInfo; // mach_msg_type_number_t infoCount = TASK_BASIC_INFO_COUNT; // kern_return_t kernReturn = task_info(mach_task_self(), // TASK_BASIC_INFO, // (task_info_t) & taskInfo, // &infoCount); // if (kernReturn == KERN_SUCCESS) // { // memory = taskInfo.resident_size / 1024.0 / 1024.0; // } // if (memory < memoryDefault) // { // LogUtil.LogError(string.Format("内存不足!"), LogType.TaskLog); // //弹出内存警告 // } // else // { // LogUtil.Log(string.Format("可以使用 ^_^"), LogType.TaskLog); // //自动取消内存警告 // LogUtil.Log(Environment.WorkingSet.ToString(), LogType.TaskLog); // } } catch (Exception e) { Console.WriteLine(e); throw; } #endif IsFinish = true; }
public static void ResGOConfig() { //获取编辑器下所有的Tag var tags = UnityEditorInternal.InternalEditorUtility.tags; var layers = UnityEditorInternal.InternalEditorUtility.layers; var datas = new Dictionary <long, ABData>(); var genPath = Application.dataPath + "/Addressable Asset/"; var filesPath = Directory.GetFiles(genPath, "*.prefab", SearchOption.AllDirectories); var info = ""; var presenceResID = new HashSet <long>(); var presenceResName = new HashSet <string>(); for (int i = 0; i < filesPath.Length; i++) { filesPath[i] = filesPath[i].Substring(filesPath[i].IndexOf("Assets", StringComparison.Ordinal)); var prefab = AssetDatabase.LoadAssetAtPath(filesPath[i], typeof(GameObject)) as GameObject; var progress = (float)i / filesPath.Length; EditorUtility.DisplayProgressBar("资源记录已知ResID进度...", info, progress); if (prefab != null) { var goBase = prefab.GetComponent <ObjectBase>(); if (goBase != null) { if (goBase.ResID > 0 && goBase.ResID / 10000000 <= 0) { presenceResID.Add(goBase.ResID); } else { goBase.ResID = 0; } } } } for (int i = 0; i < filesPath.Length; i++) { var goIndex = 0; filesPath[i] = filesPath[i].Substring(filesPath[i].IndexOf("Assets", StringComparison.Ordinal)); var prefab = AssetDatabase.LoadAssetAtPath(filesPath[i], typeof(GameObject)) as GameObject; var progress = (float)i / filesPath.Length; EditorUtility.DisplayProgressBar("资源配置刷新进度...", info, progress); if (prefab != null) { var goBase = prefab.GetComponent <ObjectBase>(); if (goBase != null && !datas.ContainsKey(goBase.ResID)) { var indexTag = 0; foreach (var tag in tags) { if (tag == goBase.ObjectTag) { break; } indexTag++; } var indexLayer = 0; var tmpLayer = layers[0]; for (int j = 0; j < goBase.ObjectLayer; j++) { indexLayer++; tmpLayer = layers[j]; } var resID = 0; if (presenceResID.Contains(goBase.ResID)) { resID = goBase.ResID; } else { resID = +indexTag * 100000 + goIndex; var reCreateIndex = true; while (reCreateIndex) { if (goIndex > 100000) { throw new Exception("超过判断"); } if (presenceResID.Add(resID)) { reCreateIndex = false; } else { goIndex++; resID = +indexTag * 100000 + goIndex; } } } goBase.ResID = resID; goBase.BaseName = goBase.gameObject.name; AssetDatabase.SaveAssets(); var path = filesPath[i]; path = filesPath[i].Substring(filesPath[i].IndexOf("Addressable Asset", StringComparison.Ordinal)); info = path; var index1 = path.IndexOf("/", StringComparison.Ordinal); var index2 = path.IndexOf(".", StringComparison.Ordinal) - 1; path = path.Substring(index1 + 1, index2 - index1); path = @"Assets\Addressable Asset\" + path; datas.Add(goBase.ResID, new ABData() { ID = goBase.ResID, Path = path, name = goBase.BaseName, Des = goBase.Des, Layer = tmpLayer, Tag = goBase.ObjectTag, }); goIndex++; if (presenceResName.Contains(goBase.gameObject.name)) { EditorUtility.ClearProgressBar(); LogTool.LogError(string.Format("资源命名重复:重复名---> {0}", goBase.gameObject.name), LogEnum.AssetLog); return; } else { presenceResName.Add(goBase.gameObject.name); } } } } if (datas.Count != 0) { AssetDatabase.SaveAssets(); } EditorUtility.ClearProgressBar(); LogTool.Log($"共产生 {datas.Count} 个GO", LogEnum.Editor); }
public NanoRdpTransport(string address, int tcpPort, int udpPort) { _address = address; _tcpPort = tcpPort; _udpPort = udpPort; _cancellationTokenSource = new CancellationTokenSource(); IPAddress hostAddr = IPAddress.Parse(address); _controlProtoEp = new IPEndPoint(hostAddr, _tcpPort); _streamingProtoEp = new IPEndPoint(hostAddr, _udpPort); _controlProtoClient = new TcpClient(AddressFamily.InterNetwork); _streamingProtoClient = new UdpClient(AddressFamily.InterNetwork); _controlProtoClient.Client.Bind(new IPEndPoint(IPAddress.Any, 0)); _streamingProtoClient.Client.Bind(new IPEndPoint(IPAddress.Any, 0)); _controlProtoClient.Connect(_controlProtoEp); _streamingProtoClient.Connect(_streamingProtoEp); ChannelContext = new NanoChannelContext(); void ProcessPacket(byte[] packetData) { try { EndianReader reader = new EndianReader(packetData); INanoPacket packet = NanoPacketFactory.ParsePacket(packetData, ChannelContext); if (packet.Header.PayloadType == NanoPayloadType.ChannelControl && packet as ChannelCreate != null) { ChannelContext.RegisterChannel((ChannelCreate)packet); } else if (packet.Header.PayloadType == NanoPayloadType.ChannelControl && packet as ChannelClose != null) { ChannelContext.UnregisterChannel((ChannelClose)packet); } else if (RemoteConnectionId == 0 && packet as ControlHandshake != null) { RemoteConnectionId = ((ControlHandshake)packet).ConnectionId; } bool success = _receiveQueue.TryAdd(packet); if (!success) { LogTool.Log($"Failed to add message to receive queue"); } } catch (NanoPackingException e) { LogTool.LogError($"Failed to parse nano packet: {e.Message}", e); } } _controlProtoClient.ConsumeReceivedPrefixed( receiveResult => ProcessPacket(receiveResult), _cancellationTokenSource.Token ); _streamingProtoClient.ConsumeReceived( receiveResult => ProcessPacket(receiveResult.Buffer), _cancellationTokenSource.Token ); Task.Run(() => { while (!_receiveQueue.IsCompleted) { try { var message = _receiveQueue.Take(); MessageReceived?.Invoke(this, new MessageReceivedEventArgs <INanoPacket>(message)); } catch (Exception e) { LogTool.LogError( e, "Calling Nano MessageReceived failed!"); } } }, _cancellationTokenSource.Token); }
/// <summary> /// 目标由GoalMgr提供 /// </summary> /// <param name="goal"></param> /// <returns></returns> public override LinkedList <IActionHandler <ActionTag> > BuildPlan(IGoal <GoalTag> goal) { LogTool.Log($"制定计划 ------"); var plan = new LinkedList <IActionHandler <ActionTag> >(); var lastAction = BuildActionTree(); if (lastAction != null) { if (lastAction.Data == null) { plan.AddLast(agent.AgentActionMgr.GetHandler(ActionTag.Idle)); } while (lastAction.Data != null) { plan.AddLast(lastAction.Data); lastAction = lastAction.Parent; } } else { LogTool.LogError($"当前节点为空"); } LogTool.Log($"------ 最终生成计划 ------"); foreach (var handler in plan) { LogTool.Log($"计划项: {handler.Action.Label}"); } LogTool.Log($"------ 生成计划结束"); return(plan); //构建Action树 MultiTreeNode <IActionHandler <ActionTag> > BuildActionTree() { //初始化默认父节点 var topTree = new MultiTreeNode <IActionHandler <ActionTag> >(null); topTree.OtherData.AddHashtableElement(CurrCost, 0); var currNode = topTree; var tuple = agent.Context.Condition.GetDiffecentTargetTags(goal); var restCurrKeys = tuple.Item1.ToList(); var resetTarget = tuple.Item2.ToList(); MultiTreeNode <IActionHandler <ActionTag> > subNode = null; MultiTreeNode <IActionHandler <ActionTag> > cheapestNode = null; //循环创建多叉树 while (!IsNodeEnd(restCurrKeys)) { //获取状态差异的Handlers var handlers = GetSubHandlers(); foreach (var handler in handlers) { subNode = new MultiTreeNode <IActionHandler <ActionTag> >(handler); subNode.OtherData.AddHashtableElement(CurrCost, GetAllCost()); subNode.Parent = currNode; cheapestNode = GetCheapestNode(subNode, cheapestNode); } currNode = cheapestNode; tuple = AIConditionExtend.GetDiffecentCondition(resetTarget, currNode.Data.Action.Effects); restCurrKeys = tuple.Item1.ToList(); resetTarget = tuple.Item2.ToList(); cheapestNode = null; } return(currNode); int GetAllCost() { var configCost = 0f; if (subNode.Data != null) { foreach (var costParameter in subNode.Data.Action.Cost) { configCost += (costParameter.value * costParameter.CostPriority) / 100; } } var currCost = currNode.OtherData.GetHashtableElement <int>(CurrCost); //上一个节点消耗 + 配置消耗 + 比较之前节点消耗 var count = AIConditionExtend.GetDiffecentCondition(resetTarget, subNode.Data.Action.Effects); return(currCost + (int)configCost + count.Item1.Count); } //获取当前节点所有可能的子节点 List <IActionHandler <ActionTag> > GetSubHandlers() { var handlers = new List <IActionHandler <ActionTag> >(); if (currNode == null) { return(handlers); } var maps = agent.AgentActionMgr.EffectActionMap; //下面进行查找相对应的Handler foreach (var key in restCurrKeys) { if (maps.ContainsKey(key)) { foreach (var handler in maps[key]) { //筛选能够执行的动作 if (!handlers.Contains(handler) && handler.Action.GetEffectsValue(key).IsRight == resetTarget.GetDiffecentCondition(key).IsRight) { handlers.Add(handler); } } } else { LogTool.LogError($"当前没有动作能够实现从当前状态切换到目标状态,无法实现的键值为: {key}"); } } handlers = handlers.OrderByDescending(handler => handler.Action.Priority).ToList(); return(handlers); } } }