92 lines
2.6 KiB
C#
92 lines
2.6 KiB
C#
|
|
|
||
|
|
using System;
|
||
|
|
using BehaviorDesigner.Runtime;
|
||
|
|
using Cysharp.Threading.Tasks;
|
||
|
|
using Framework;
|
||
|
|
using Gameplay.AI;
|
||
|
|
using UnityEngine;
|
||
|
|
|
||
|
|
namespace Gameplay.BT
|
||
|
|
{
|
||
|
|
public partial class BTImplement : Singlenton<BTImplement>
|
||
|
|
{
|
||
|
|
private BehaviorManager _behaviorManager;
|
||
|
|
|
||
|
|
public void Init()
|
||
|
|
{
|
||
|
|
try
|
||
|
|
{
|
||
|
|
var gameObject = new GameObject();
|
||
|
|
gameObject.name = "BehaviorManager";
|
||
|
|
_behaviorManager = gameObject.AddComponent<BehaviorManager>();
|
||
|
|
_behaviorManager.UpdateInterval = UpdateIntervalType.Manual;
|
||
|
|
}
|
||
|
|
catch (Exception e)
|
||
|
|
{
|
||
|
|
DebugUtil.LogError($" BTImplement Init error: {e.Message}");
|
||
|
|
}
|
||
|
|
DebugUtil.Log($" BTImplement Init success");
|
||
|
|
}
|
||
|
|
|
||
|
|
public void Update(float deltaTime)
|
||
|
|
{
|
||
|
|
_behaviorManager.Update();
|
||
|
|
}
|
||
|
|
|
||
|
|
public void Release()
|
||
|
|
{
|
||
|
|
ClearPool();
|
||
|
|
DebugUtil.Log("BTImplement Release success");
|
||
|
|
}
|
||
|
|
|
||
|
|
public async UniTask<BehaviorTree> RegisterAI(GameObject go, string aiName)
|
||
|
|
{
|
||
|
|
try
|
||
|
|
{
|
||
|
|
var bt = go.GetComponent<BehaviorTree>();
|
||
|
|
if (bt == null)
|
||
|
|
{
|
||
|
|
bt = go.AddComponent<BehaviorTree>();
|
||
|
|
bt.StartWhenEnabled = false;
|
||
|
|
}
|
||
|
|
|
||
|
|
bt.DisableBehavior();
|
||
|
|
bt.ExternalBehavior = await GetBehavior(aiName);
|
||
|
|
bt.StartWhenEnabled = true;
|
||
|
|
bt.EnableBehavior();
|
||
|
|
|
||
|
|
DebugUtil.LogG($"BT gameObject {go.name} register ai: {aiName}, behavior: {bt.ExternalBehavior?.name}");
|
||
|
|
return bt;
|
||
|
|
}
|
||
|
|
catch (Exception e)
|
||
|
|
{
|
||
|
|
DebugUtil.LogError($"RegisterAI error: {e.Message}, aiName: {aiName}, go: {go.name}");
|
||
|
|
}
|
||
|
|
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
|
||
|
|
public void UnRegisterAI(GameObject go)
|
||
|
|
{
|
||
|
|
try
|
||
|
|
{
|
||
|
|
var bt = go.GetComponent<BehaviorTree>();
|
||
|
|
if (bt == null)
|
||
|
|
{
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
bt.DisableBehavior();
|
||
|
|
ReleaseBehavior(bt.ExternalBehavior.name.Replace("(Clone)", ""), bt.ExternalBehavior);
|
||
|
|
bt.ExternalBehavior = null;
|
||
|
|
|
||
|
|
DebugUtil.LogG($"BT gameObject {go.name} unregister ai");
|
||
|
|
}
|
||
|
|
catch (Exception e)
|
||
|
|
{
|
||
|
|
DebugUtil.LogError($"UnRegisterAI error: {e.Message}, go: {go.name}");
|
||
|
|
}
|
||
|
|
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|