This commit is contained in:
CortexCore
2023-11-06 01:17:23 +08:00
parent bd40165ade
commit 5446067f91
114 changed files with 2023 additions and 414 deletions

View File

@@ -1,12 +1,14 @@
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using BITKit.Animations;
namespace BITKit.Entities
{
public sealed class EntityAnimator : EntityComponent
public sealed class EntityAnimator : EntityBehavior
{
[SerializeField] private Animator[] animators;
[SerializeField] private UnityAnimator[] animators;
[SerializeReference, SubclassSelector] private References[] animationKeyWords;
[SerializeReference, SubclassSelector] private References _rootVelocity;
[SerializeReference, SubclassSelector] private References[] boolParameters;
@@ -18,18 +20,18 @@ namespace BITKit.Entities
}
public override void OnStart()
{
entity.AddListener<string>(Constant.Animation.Play, Play);
UnityEntity.AddListener<string>(Constant.Animation.Play, Play);
}
private void Play(string animationName)
{
if (enabled is false) return;
if (animationKeyWords.Length is 0 || keyWords.Contains(animationName))
{
animators.ForEach(x =>
{
if (!x.isActiveAndEnabled) return;
animationName = animationName.Replace(".", "_");
x.SetTrigger(animationName);
x.Play(animationName);
});
}
}
@@ -40,7 +42,7 @@ namespace BITKit.Entities
animators.ForEach(x =>
{
if (x.isActiveAndEnabled)
x.SetBool(boolPar, entity.Get<bool>(boolPar));
x.animator.SetBool(boolPar, UnityEntity.Get<bool>(boolPar));
});
}
foreach (var floatPar in floatParameters)
@@ -48,18 +50,22 @@ namespace BITKit.Entities
animators.ForEach(x =>
{
if (x.isActiveAndEnabled)
x.SetFloat(floatPar, entity.Get<float>(floatPar));
x.animator.SetFloat(floatPar, UnityEntity.Get<float>(floatPar));
});
}
}
private void OnAnimatorMove()
{
entity.Set(_rootVelocity, animators[0].velocity);
if (enabled is false) return;
if (_rootVelocity is not null && UnityEntity is not null)
UnityEntity.Set(_rootVelocity, animators[0].animator.velocity);
}
// ReSharper disable once UnusedMember.Local
private void AnimationEvent(string eventName)
{
entity.Invoke(Constant.Animation.OnEvent, eventName);
UnityEntity.Invoke(Constant.Animation.OnEvent, eventName);
}
}
}

View File

@@ -4,12 +4,12 @@ using UnityEngine;
using BITKit.Sensors;
namespace BITKit.Entities
{
public class EntityAudioObject : EntityComponent, IAudioObject
public class EntityAudioObject : EntityBehavior, IAudioObject
{
float volume;
public override void OnStart()
{
entity.AddListener<AudioSO>(OnAuioSO);
UnityEntity.AddListener<AudioSO>(OnAuioSO);
}
public override void OnFixedUpdate(float deltaTime)
{

View File

@@ -2,7 +2,7 @@ using BITKit.Entities.Player;
using UnityEngine;
namespace BITKit.Entities
{
public class EntityCamera : EntityPlayerComponent
public class EntityCamera : EntityPlayerBehavior
{
[Header(Constant.Header.Components)]
public Behaviour aliveCamera;
@@ -11,7 +11,7 @@ namespace BITKit.Entities
[SerializeReference, SubclassSelector] public IReference _onSetAlive;
public override void OnAwake()
{
var heal = entity.Get<IHealth>();
var heal = UnityEntity.Get<IHealth>();
heal.OnSetAlive += OnSetAlive;
}
private void OnSetAlive(bool alive)

View File

@@ -4,7 +4,7 @@ using UnityEngine;
using UnityEngine.Rendering;
namespace BITKit.Entities.Player.Character
{
public class EntityCharacter : EntityPlayerComponent
public class EntityCharacter : EntityPlayerBehavior
{
[Header(Constant.Header.Components)]
[SerializeField] private Renderer[] fpvRenderer = Array.Empty<Renderer>();
@@ -13,7 +13,7 @@ namespace BITKit.Entities.Player.Character
[SerializeReference, SubclassSelector] public References _getDamage;
public override void OnStart()
{
var heal = entity.Get<IHealth>();
var heal = UnityEntity.Get<IHealth>();
heal.OnSetAlive += OnSetAlive;
heal.OnSetHealthPoint += OnSetHP;
}
@@ -33,7 +33,7 @@ namespace BITKit.Entities.Player.Character
}
private void OnSetHP(int hp)
{
entity.Invoke<string>(Constant.Animation.Play, _getDamage);
UnityEntity.Invoke<string>(Constant.Animation.Play, _getDamage);
}
private void SetFPV(bool isFpv)
{

View File

@@ -6,7 +6,7 @@ using UnityEngine.InputSystem;
namespace BITKit
{
public class NavAgentMovement: StateBasedComponent<IEntityMovementState>,IEntityMovement
public class NavAgentMovement: StateBasedBehavior<IEntityMovementState>,IEntityMovement
{
#region
[SerializeField] private NavMeshAgent agent;
@@ -67,8 +67,8 @@ namespace BITKit
GroundVelocity = _groundVelocity;
IsGrounded = agent.isOnOffMeshLink is false;
entity.Set<bool>("IsMoving",Velocity.sqrMagnitude>=0.16f);
entity.Set<float>("SqrMagnitude",Velocity.sqrMagnitude);
UnityEntity.Set<bool>("IsMoving",Velocity.sqrMagnitude>=0.16f);
UnityEntity.Set<float>("SqrMagnitude",Velocity.sqrMagnitude);
if (!isDead) return;

View File

@@ -6,7 +6,7 @@ using UnityEngine.InputSystem;
namespace BITKit.Entities.Movement
{
public class RigidbodyBasedMovement : StateBasedComponent<IEntityMovementState>,IEntityMovement
public class RigidbodyBasedMovement : StateBasedBehavior<IEntityMovementState>,IEntityMovement
{
[SerializeField] private new Rigidbody rigidbody;
[SerializeField] private Animator animator;
@@ -20,6 +20,11 @@ namespace BITKit.Entities.Movement
public Vector3 GroundVelocity { get; }
public Vector3 AngularVelocity { get; }
public bool IsGrounded { get; }
[Inject(true)]
private IHealth health;
public void SyncMovement(Vector3 velocity, Vector3 position, Quaternion rotation, bool isGrounded)
{
}
@@ -37,6 +42,20 @@ namespace BITKit.Entities.Movement
}
public event Action<object> OnCommand;
public override void OnAwake()
{
base.OnAwake();
if (health is not null)
{
health.OnSetAlive += OnSetAlive;
}
}
private void OnSetAlive(bool obj)
{
rigidbody.isKinematic = !obj;
}
public override void OnFixedUpdate(float deltaTime)
{
rigidbody.MovePosition(rigidbody.position + Velocity * deltaTime

View File

@@ -6,7 +6,7 @@ using UnityEngine;
namespace BITKit
{
public class AutoHealComponent : EntityComponent,IDamageCallback
public class AutoHealBehavior : EntityBehavior,IDamageCallback
{
[SerializeField] private IntervalUpdate healDelayInterval;
[SerializeField] private IntervalUpdate healInterval;
@@ -14,17 +14,12 @@ namespace BITKit
private readonly ValidHandle allowHeal = new();
[Inject]
private IHealth _health;
public override void Initialize(IEntity _entity)
{
base.Initialize(_entity);
_health.OnSetAlive += OnSetAlive;
_health.OnSetHealthPoint += OnSetHP;
_entity.RegisterCallback<IDamageCallback>(this);
}
public override void OnStart()
{
_health = entity.Get<IHealth>();
_health = UnityEntity.Get<IHealth>();
_health.OnSetAlive += OnSetAlive;
_health.OnSetHealthPoint += OnSetHP;
}
private void Update()

View File

@@ -1,53 +1,50 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using BITKit.Entities;
using UnityEngine;
namespace BITKit
{
public class AutoRespawnComponent : EntityComponent,IAction
public class AutoRespawnBehavior : EntityBehavior,IAction
{
[SerializeField] private IntervalUpdate respawnInterval;
private bool requestRespawn;
[Inject] private IHealth _health;
private int _initialHp;
private CancellationTokenSource _cancellationTokenSource;
public override void OnAwake()
{
_initialHp=_health.HealthPoint;
_health.OnSetAlive += OnSetAlive;
_health.OnSetHealthPoint += OnSetHP;
}
public override void OnUpdate(float deltaTime)
{
if (requestRespawn && respawnInterval.AllowUpdate)
{
requestRespawn = false;
Execute();
}
}
public void OnSetAlive(bool alive)
private async void OnSetAlive(bool alive)
{
if (alive)
{
requestRespawn = false;
_cancellationTokenSource?.Cancel();
}
else
{
respawnInterval.Reset();
requestRespawn = true;
_cancellationTokenSource?.Cancel();
_cancellationTokenSource = new CancellationTokenSource();
try
{
await Task.Delay(TimeSpan.FromSeconds(respawnInterval.Interval), _cancellationTokenSource.Token);
destroyCancellationToken.ThrowIfCancellationRequested();
Execute();
}
catch(MissingReferenceException){}
catch (OperationCanceledException){}
}
}
public void OnSetHP(int hp)
{
}
public void Execute()
{
if (TryGetComponent<IHealth>(out var health))
{
health.HealthPoint = 100;
}
if (_health.IsAlive is false)
_health.HealthPoint = _initialHp;
}
}

View File

@@ -61,8 +61,8 @@ namespace BITKit.Entities
}
public record DamageMessage
{
public IEntity Initiator;
public IEntity Target;
public IUnityEntity Initiator;
public IUnityEntity Target;
public bool RawDamage;
public int Damage;
public IDamagable Hit;
@@ -75,7 +75,7 @@ namespace BITKit.Entities
}
public interface IDamagable
{
IEntity Entity { get; }
IUnityEntity UnityEntity { get; }
Rigidbody Rigidbody { get; }
void GiveDamage(DamageMessage message);
}
@@ -99,11 +99,6 @@ namespace BITKit.Entities
damageMessage.Initiator?.Invoke(damageMessage);
damageMessage.Target?.Invoke(damageMessage);
foreach (var x in damageMessage.Target?.GetCallbacks<IDamageCallback>()!)
{
x.OnGetDamage(damageMessage);
}
OnEntityDamaged?.Invoke(damageMessage);
if (heal.IsAlive is false)
{

View File

@@ -26,7 +26,7 @@ namespace BITKit.Entities
bool IsAlive { get; }
}
[CustomType(typeof(IHealth))]
public class EntityHealth : EntityComponent, IHealth
public class EntityHealth : EntityBehavior, IHealth
{
[Header(Constant.Header.Settings)]
[SerializeField] private int healthPoint = 100;
@@ -49,7 +49,7 @@ namespace BITKit.Entities
public bool IsAlive { get; private set; }
public override void OnAwake()
{
entity.AddListener<DamageMessage>(OnGetDamage);
UnityEntity.AddListener<DamageMessage>(OnGetDamage);
}
public override void OnStart()
@@ -83,7 +83,7 @@ namespace BITKit.Entities
private void OnGetDamage(DamageMessage damageMessage)
{
if (damageMessage.Target != entity) return;
if (damageMessage.Target != UnityEntity) return;
if (IsAlive is false) return;
var damage = damageMessage.Damage;
foreach (var x in OnDamageFactory.CastAsFunc().Reverse())

View File

@@ -9,7 +9,7 @@ using UnityEngine.Events;
namespace BITKit.Entities
{
public class GetDamageComponent : EntityComponent
public class GetDamageBehavior : EntityBehavior
{
private readonly Queue<DamageMessage> DamageMessages = new();
[SerializeField] private UnityEvent<DamageMessage> onGetDamage;
@@ -17,11 +17,11 @@ namespace BITKit.Entities
private IDamageCallback[] callbacks;
public override void OnAwake()
{
entity.AddListener<DamageMessage>(OnGetDamage);
UnityEntity.AddListener<DamageMessage>(OnGetDamage);
}
private void OnGetDamage(DamageMessage obj)
{
if (obj.Target != entity) return;
if (obj.Target != UnityEntity) return;
DamageMessages.Enqueue(obj);
onGetDamage?.Invoke(obj);
foreach (var x in callbacks)

View File

@@ -4,13 +4,13 @@ using UnityEngine;
using BITKit;
namespace BITKit.Entities
{
public class EntityHitbox : EntityComponent,IDamagable
public class EntityHitbox : EntityBehavior,IDamagable
{
IEntity IDamagable.Entity => entity;
IUnityEntity IDamagable.UnityEntity => UnityEntity;
public Rigidbody Rigidbody => m_rigidbody;
public void GiveDamage(DamageMessage message)
{
entity.Invoke(message);
UnityEntity.Invoke(message);
}
[SerializeField]private Rigidbody m_rigidbody;

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: e6a1d9b4067d2d84da86a7e043b40806
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,4 @@
{
"name": "BITKit.Entities.InputSystem",
"references":[ "GUID:14fe60d984bf9f84eac55c6ea033a8f4", "GUID:f6155d9ae143f3949ac54e8355593d6c", "GUID:7efac18f239530141802fb139776f333", "GUID:709caf8d7fb6ef24bbba0ab9962a3ad0" ]
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 7fa5fe8aad740144c9ddda741d067c44
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,68 @@
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
namespace BITKit.Entities.InputSystem
{
public class EntityInputSystem : EntityBehavior
{
protected readonly InputActionGroup inputActionGroup = new()
{
allowGlobalActivation = true
};
[Inject(true)]
private IHealth _health;
[Inject(true)]
private IEntityOverride _override;
#if UNITY_EDITOR
[SerializeField,HideInInspector] internal bool Allow;
#endif
public override void Initialize(IEntity _entity)
{
base.Initialize(_entity);
UnityEntity.AddService(inputActionGroup);
}
public override void OnAwake()
{
base.OnAwake();
inputActionGroup.allowInput.AddListener(x=>Allow=x);
if (_health is not null)
{
_health.OnSetAlive += x =>
{
inputActionGroup.allowInput.SetElements(_health,x);
};
}
if (_override is not null)
{
_override.OnOverride += x =>
{
inputActionGroup.allowInput.SetDisableElements(_override,x);
};
}
}
}
#if UNITY_EDITOR
[CustomEditor(typeof(EntityInputSystem))]
public sealed class EntityInputSystemInspector : BITInspector<EntityInputSystem>
{
public override VisualElement CreateInspectorGUI()
{
FillDefaultInspector();
var checkBox = root.Create<Toggle>();
checkBox.label = "Allow Input";
checkBox.SetEnabled(false);
checkBox.BindProperty(serializedObject.FindProperty(nameof(EntityInputSystem.Allow)));
return root;
}
}
#endif
}

View File

@@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: 5ca4ab5daca5d054caf8c917c9ca6aa7
guid: 34b176396debf404d9190a6fbde6ff77
MonoImporter:
externalObjects: {}
serializedVersion: 2

View File

@@ -7,7 +7,7 @@ using UnityEngine.InputSystem.Interactions;
namespace BITKit.Entities.Player
{
[CustomType(typeof(ISelector))]
public class EntityInteractive : EntityPlayerComponent,ISelector
public class EntityInteractive : EntityPlayerBehavior,ISelector
{
[Header(Constant.Header.Settings)]
[SerializeReference, SubclassSelector] private ISensor sensor;
@@ -17,8 +17,6 @@ namespace BITKit.Entities.Player
private IntervalUpdate cd = new(0.08f);
[Inject]
private IHealth _health;
[Inject]
private InputActionGroup _inputActionReference;
public override void OnStart()
{
@@ -82,6 +80,10 @@ namespace BITKit.Entities.Player
if (monoBehaviour.TryGetComponentAny<IAction>(out var action))
{
action.Execute();
}
else
{
}
selected.SetSelectionState(SelectionState.Active);
OnActive?.Invoke(selected);

View File

@@ -6,7 +6,7 @@ using UnityEngine.Events;
using Cysharp.Threading.Tasks;
namespace BITKit.Entities
{
public class EntityLocomotion : EntityComponent
public class EntityLocomotion : EntityBehavior
{
[Header(Constant.Header.Settings)]

View File

@@ -8,23 +8,45 @@ using UnityEngine;
namespace BITKit.Entities
{
[CustomType(typeof(IEntityPhysics))]
public class EntityPhysics : EntityComponent,IEntityPhysics
public class EntityPhysics : EntityBehavior,IEntityPhysics
{
[SerializeField] private Animator animator;
[SerializeField] private Rigidbody[] rigidbodies;
[SerializeField] private Collider[] ragdollColliders;
[SerializeField] private Joint joint;
[SerializeField] private Joint[] joints;
[SerializeField] private new Rigidbody rigidbody;
private CancellationToken _cancellationToken;
[Inject]
private IHealth _health;
private readonly Dictionary<Joint,ConfigurableJointMotion> _jointXMotions=new();
private readonly Dictionary<Joint,ConfigurableJointMotion> _jointYMotions=new();
private readonly Dictionary<Joint,ConfigurableJointMotion> _jointZMotions=new();
private readonly Dictionary<Joint,ConfigurableJointMotion> _jointAngularXMotions=new();
private readonly Dictionary<Joint,ConfigurableJointMotion> _jointAngularYMotions=new();
private readonly Dictionary<Joint,ConfigurableJointMotion> _jointAngularZMotions=new();
public override void OnAwake()
{
_health.OnSetAlive += OnSetAlive;
_health.OnSetHealthPoint += OnSetHP;
_cancellationToken = entity.Get<CancellationToken>();
_cancellationToken = UnityEntity.Get<CancellationToken>();
foreach (var x in joints)
{
switch (x)
{
case ConfigurableJoint configurableJoint:
_jointXMotions.Add(configurableJoint,configurableJoint.xMotion);
_jointYMotions.Add(configurableJoint,configurableJoint.yMotion);
_jointZMotions.Add(configurableJoint,configurableJoint.zMotion);
_jointAngularXMotions.Add(configurableJoint,configurableJoint.angularXMotion);
_jointAngularYMotions.Add(configurableJoint,configurableJoint.angularYMotion);
_jointAngularZMotions.Add(configurableJoint,configurableJoint.angularZMotion);
break;
}
}
}
private async void OnSetAlive(bool alive)
private async void OnSetAlive(bool alive)
{
IsPhysics = !alive;
if (animator)
@@ -38,15 +60,29 @@ namespace BITKit.Entities
}
catch (OperationCanceledException)
{
}
if (alive is false && joint is not null)
foreach (var joint in joints)
{
Destroy(joint);
switch (joint)
{
case ConfigurableJoint configurableJoint:
configurableJoint.xMotion = alive ? _jointXMotions[joint] : ConfigurableJointMotion.Free;
configurableJoint.yMotion = alive ? _jointYMotions[joint] : ConfigurableJointMotion.Free;
configurableJoint.zMotion = alive ? _jointZMotions[joint] : ConfigurableJointMotion.Free;
configurableJoint.angularXMotion =
alive ? _jointAngularXMotions[joint] : ConfigurableJointMotion.Free;
configurableJoint.angularYMotion =
alive ? _jointAngularYMotions[joint] : ConfigurableJointMotion.Free;
configurableJoint.angularZMotion =
alive ? _jointAngularZMotions[joint] : ConfigurableJointMotion.Free;
break;
}
}
}
public void OnSetHP(int hp)
{
}

View File

@@ -6,7 +6,7 @@ using UnityEngine;
namespace BITKit.Entities.Slot
{
[CustomType(typeof(IEntitySlot<Transform>))]
public sealed class UnityEntitySlot : EntityComponent, IEntitySlot<Transform>
public sealed class UnityEntitySlot : EntityBehavior, IEntitySlot<Transform>
{
[SerializeField] private SerializedDictionary<string,Transform> dictionary = new();
public IDictionary<string, Transform> Slots => dictionary;

View File

@@ -5,7 +5,7 @@ using UnityEngine;
namespace BITKit.Entities
{
public class SlotComponent : EntityComponent
public class SlotBehavior : EntityBehavior
{
public SerializedDictionary<string,Transform> slots;
}

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 717c72a7a267b5341a874e6d50d7df49
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,20 @@
{
"name": "BITKit.Entities.VFX",
"rootNamespace": "",
"references": [
"GUID:14fe60d984bf9f84eac55c6ea033a8f4",
"GUID:709caf8d7fb6ef24bbba0ab9962a3ad0",
"GUID:ea5474181b324dd49a5976cd68f44f18",
"GUID:d525ad6bd40672747bde77962f1c401e",
"GUID:49b49c76ee64f6b41bf28ef951cb0e50"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 1eb13dc7c3cb5a444877a995967ed591
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,27 @@
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace BITKit.Entities.VFX
{
public class EntityVFXPlayer : EntityBehavior
{
[SerializeReference,SubclassSelector] private IReference[] vfxReferences;
[SerializeField] private VFXPlayer vfxPlayer;
private readonly List<string> keyWords=new();
public override void OnAwake()
{
base.OnAwake();
keyWords.AddRange(vfxReferences.Select(x=>x.Value));
UnityEntity.AddListener<string>(Constant.Animation.Play, Play);
}
private void Play(string animationName)
{
if (isActiveAndEnabled is false) return;
if (keyWords.Contains(animationName) is false) return;
vfxPlayer.Execute();
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: eac859befd6ba3349b2cf8acb119d2de
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -5,29 +5,27 @@ using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using BITKit.Core.Entites;
using BITKit.Entities;
using Cysharp.Threading.Tasks;
using UnityEngine.UIElements;
// ReSharper disable RedundantTypeArgumentsOfMethod
namespace BITKit.Entities
{
public class Entity : MonoBehaviour, IEntity
public class Entity : MonoBehaviour, IUnityEntity
{
private readonly GenericEvent genericEvent = new();
private readonly Processor processor = new();
public IEntityComponent[] entityComponents { get; set; }
public ulong Id { get; private set; }
public CancellationToken CancellationToken => _cancellationToken;
public CancellationToken CancellationToken { get; private set; }
public IEntityBehavior[] Behaviors { get;private set; }
public IEntityComponent[] Components => Behaviors.Cast<IEntityComponent>().ToArray();
Core.Entites.IEntityComponent[] Core.Entites.IEntity.Components => _components;
bool Core.Entites.IEntity.RegisterComponent<T>(T component)
bool Entities.IEntity.RegisterComponent<T>(T component)
{
throw new InvalidOperationException("Unity Entity can't register component");
}
IServiceProvider Core.Entites.IEntity.ServiceProvider=> throw new InvalidOperationException("Unity Entity can't register component");
IServiceProvider Entities.IEntity.ServiceProvider=> throw new InvalidOperationException("Unity Entity can't register component");
public void Inject(object obj)
{
foreach (var fieldInfo in obj
@@ -44,7 +42,7 @@ namespace BITKit.Entities
{
case null:
break;
case Core.Entites.IEntityComponent entityComponent:
case Entities.IEntityComponent entityComponent:
if(entityComponent.Entity.Id == Id)
continue;
break;
@@ -61,23 +59,37 @@ namespace BITKit.Entities
}
else if(attribute?.CanBeNull is false)
{
BIT4Log.Warning<Entity>($"{name}未找到{type.FullName}");
BIT4Log.Warning<Entity>(genericEvent.GetDiagnostics());
BIT4Log.Warning<Entity>($"{name}未找到{obj.GetType().Name}需要的{type.FullName}");
//BIT4Log.Warning<Entity>(genericEvent.GetDiagnostics());
}
}
}
private CancellationToken _cancellationToken;
public void AddService<T>(T service)
{
AddService(typeof(T),service);
}
public void AddService(object service)
{
AddService(service.GetType(),service);
}
public void AddService(Type type, object service)
{
genericEvent.Set(type,service);
genericEvent.Set(type.FullName, service);
genericEvent.SetDirect(type.FullName,service);
}
private bool isInitialized;
private Core.Entites.IEntityComponent[] _components => entityComponents.Cast<Core.Entites.IEntityComponent>().ToArray();
private void Awake()
{
Id = (ulong)Guid.NewGuid().GetHashCode();
_cancellationToken = gameObject.GetCancellationTokenOnDestroy();
Set(_cancellationToken);
entityComponents = GetComponentsInChildren<IEntityComponent>(true).Distinct().ToArray();
CancellationToken = gameObject.GetCancellationTokenOnDestroy();
Set(CancellationToken);
Behaviors = GetComponentsInChildren<IEntityBehavior>(true).Distinct().ToArray();
UnityEntitiesService.Register(this);
}
private void Start()
@@ -85,6 +97,7 @@ namespace BITKit.Entities
try
{
var monoBehaviours = GetComponentsInChildren<MonoBehaviour>(true);
Behaviors.ForEach(x => x.Initialize(this));
foreach (var x in monoBehaviours)
{
foreach (var att in x
@@ -95,9 +108,7 @@ namespace BITKit.Entities
.OfType<CustomTypeAttribute>()
)
{
genericEvent.Set(att.Type,x);
genericEvent.Set(att.Type.FullName, x);
genericEvent.SetDirect(att.Type.FullName,x);
AddService(att.Type, x);
}
genericEvent.Set(x.GetType(),x);
}
@@ -105,10 +116,10 @@ namespace BITKit.Entities
{
Inject(x);
}
entityComponents.ForEach(x => x.Initialize(this));
entityComponents.ForEach(x => x.OnAwake());
entityComponents.ForEach(x => x.OnStart());
Behaviors.ForEach(x => x.OnAwake());
Behaviors.ForEach(x => x.OnStart());
isInitialized = true;
}
catch (Exception e)
@@ -122,21 +133,21 @@ namespace BITKit.Entities
{
if (isInitialized)
{
entityComponents.ForEach(x => x.OnDestroyComponent());
Behaviors.ForEach(x => x.OnDestroyComponent());
}
UnityEntitiesService.UnRegister(this);
}
private void Update()
{
entityComponents.ForEach(x => x.OnUpdate(Time.deltaTime));
Behaviors.ForEach(x => x.OnUpdate(Time.deltaTime));
}
private void FixedUpdate()
{
entityComponents.ForEach(x => x.OnFixedUpdate(Time.fixedDeltaTime));
Behaviors.ForEach(x => x.OnFixedUpdate(Time.fixedDeltaTime));
}
private void LateUpdate()
{
entityComponents.ForEach(x => x.OnLateUpdate(Time.deltaTime));
Behaviors.ForEach(x => x.OnLateUpdate(Time.deltaTime));
}
public void AddListener<T>(Action<T> action) => genericEvent.AddListener<T>(action);
public void Invoke<T>(T value) => genericEvent.Invoke<T>(value);
@@ -155,42 +166,6 @@ namespace BITKit.Entities
}
public void Set<T>(T value) => genericEvent.Set<T>(value);
public void Set<T>(string key = Constant.System.Internal, T value = default) => genericEvent.Set<T>(key, value);
public T GetContext<T>(T value = default) => processor.GetContext<T>(value);
public void AddProcessor<T>(Func<T, T> func) => processor.AddProcessor<T>(func);
public void RemoveProcessor<T>(Func<T, T> func) => processor.RemoveProcessor<T>(func);
public T GetContext<T>(string key, T value) => processor.GetContext<T>(value);
public void AddProcessor<T>(string key, Func<T, T> func) => processor.AddProcessor<T>(key, func);
public void RemoveProcessor<T>(string key, Func<T, T> func) => processor.RemoveProcessor<T>(key, func);
public void RegisterCallback<T>(T t)
{
var value = GetCallbacks<T>() as List<T>;
value!.Add(t);
}
public void UnRegisterCallback<T>(T t)
{
var value = GetCallbacks<T>() as List<T>;
value!.Remove(t);
}
public IEnumerable<T> GetCallbacks<T>()
{
var value = Get<List<T>>(nameof(ICallback)).CreateOrAddIfEmety(() =>
{
List<T> newList = new();
Set<List<T>>(nameof(ICallback), newList);
return newList;
});
if (value is null)
{
Debug.LogWarning("List is Null");
}
return value;
}
}
#if UNITY_EDITOR
[UnityEditor.CustomEditor(typeof(Entity))]

View File

@@ -0,0 +1,38 @@
using System;
using BITKit.Entities;
#if UNITY_EDITOR
using UnityEditor;
#endif
using UnityEngine;
namespace BITKit.Entities
{
public abstract class EntityBehavior : MonoBehaviour, IEntityBehavior
{
public IEntity Entity { get; set; }
public IUnityEntity UnityEntity { get; private set; }
protected Transform Transform { get; private set; }
private IUnityEntity _mUnityEntity;
public virtual void Initialize(IEntity _entity)
{
Transform = transform;
UnityEntity = _entity as IUnityEntity;
Entity = _entity;
}
public virtual void OnAwake() { }
public virtual void OnStart() { }
public virtual void OnUpdate(float deltaTime) { }
public virtual void OnFixedUpdate(float deltaTime) { }
public virtual void OnLateUpdate(float deltaTime) { }
public virtual void OnDestroyComponent() { }
}
#if UNITY_EDITOR
[CanEditMultipleObjects]
[CustomEditor(typeof(EntityBehavior), true)]
public class EntityComponentInspector : BITInspector<EntityBehavior>
{
}
#endif
}

View File

@@ -1,47 +0,0 @@
using System;
#if UNITY_EDITOR
using UnityEditor;
#endif
using UnityEngine;
namespace BITKit.Entities
{
public interface IEntityComponent:BITKit.Core.Entites.IEntityComponent
{
IEntity entity { get; }
void Initialize(IEntity _entity);
void OnUpdate(float deltaTime);
void OnFixedUpdate(float deltaTime);
void OnLateUpdate(float deltaTime);
void OnDestroyComponent();
}
public abstract class EntityComponent : MonoBehaviour, IEntityComponent
{
public IEntity entity { get; private set; }
protected Transform Transform { get; private set; }
private IEntity mEntity;
public virtual void Initialize(IEntity _entity)
{
Transform = transform;
entity = _entity;
Entity = _entity;
}
public virtual void OnAwake() { }
public virtual void OnStart() { }
public virtual void OnUpdate(float deltaTime) { }
public virtual void OnFixedUpdate(float deltaTime) { }
public virtual void OnLateUpdate(float deltaTime) { }
public virtual void OnDestroyComponent() { }
public virtual Type BaseType => GetType();
public Core.Entites.IEntity Entity { get; set; }
}
#if UNITY_EDITOR
[CanEditMultipleObjects]
[CustomEditor(typeof(EntityComponent), true)]
public class EntityComponentInspector : BITInspector<EntityComponent>
{
}
#endif
}

View File

@@ -1,19 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace BITKit.Entities
{
public class EntityIdComponent : EntityComponent
{
public ulong Id;
public string Name;
public override void Initialize(IEntity _entity)
{
if (Id is 0) Id = (ulong)Guid.NewGuid().GetHashCode();
base.Initialize(_entity);
_entity.Set(this);
}
}
}

View File

@@ -11,12 +11,8 @@ namespace BITKit.Entities
void RemoveOverride(object key);
event Action<bool> OnOverride;
}
public interface IEntityOverrideCallback
{
void OnEntryOverride(bool @override);
}
[CustomType(typeof(IEntityOverride))]
public class EntityOverride : EntityComponent,IEntityOverride
public class EntityOverride : EntityBehavior,IEntityOverride
{
[SerializeField,ReadOnly] private bool isOvering;
public bool IsOvering => _allowOverrideHandle;
@@ -25,10 +21,10 @@ namespace BITKit.Entities
public void RemoveOverride(object key)=>_allowOverrideHandle.RemoveElement(key);
public event Action<bool> OnOverride;
public override void Initialize(IEntity _entity)
public override void Initialize(IEntity entity)
{
base.Initialize(_entity);
_entity.Set<IEntityOverride>(this);
base.Initialize(entity);
UnityEntity.Set<IEntityOverride>(this);
}
public override void OnAwake()
{

View File

@@ -2,36 +2,38 @@ using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using BITKit.Core.Entites;
using BITKit.Entities;
using UnityEngine;
using UnityEngine.AddressableAssets;
namespace BITKit.Entities
{
/// <summary>Entity接口用于复杂实体</summary>
public interface IEntity :BITKit.Core.Entites.IEntity,IGenericEvent<string>, IDatabase, IProcessor, ICallback
public interface IUnityEntity :Entities.IEntity,IGenericEvent<string>, IDatabase
{
IEntityComponent[] entityComponents { get; set; }
void AddService<T>(T service);
void AddService(object service);
void AddService(Type type, object service);
}
public class IEntityReader : NetMessageReader<IEntity>
public class IEntityReader : NetMessageReader<IUnityEntity>
{
public override IEntity ReadBinary(BinaryReader reader)
public override IUnityEntity ReadBinary(BinaryReader reader)
{
var id = reader.ReadInt32();
var path = reader.ReadString();
var entity = DI.Get<IEntitiesService>().Entities[id];
return (IEntity)entity;
return (IUnityEntity)entity;
}
public override void WriteBinary(BinaryWriter writer, IEntity value)
public override void WriteBinary(BinaryWriter writer, IUnityEntity value)
{
writer.Write(value.Id);
writer.Write(value.Id);
}
private IEntity Create(int id, string path)
private IUnityEntity Create(int id, string path)
{
var entity = Addressables
.LoadAssetAsync<GameObject>(path)
.WaitForCompletion()
.GetComponent<IEntity>();
.GetComponent<IUnityEntity>();
return entity;
}
}

View File

@@ -7,7 +7,7 @@ using UnityEngine;
namespace BITKit.Entities
{
public class StateBasedComponent<T> : EntityComponent,IStateMachine<T> where T : IState
public class StateBasedBehavior<T> : EntityBehavior,IStateMachine<T> where T : IState
{
[SerializeField] private MonoStateMachine<T> stateMachine;
public bool Enabled
@@ -28,9 +28,9 @@ namespace BITKit.Entities
remove => stateMachine.OnStateChanged -= value;
}
public IDictionary<Type, T> StateDictionary => stateMachine.StateDictionary;
public override void Initialize(IEntity _entity)
public override void Initialize(IEntity entity)
{
base.Initialize(_entity);
base.Initialize(entity);
if (stateMachine is null)
{
Debug.LogWarning(GetType().Name);

View File

@@ -4,13 +4,12 @@ using System.Collections.Generic;
using System.Linq;
using System.Threading;
using BITKit;
using BITKit.Core.Entites;
using BITKit.Entities;
using UnityEngine;
using Cysharp.Threading.Tasks;
using UnityEngine.Pool;
using IEntity = BITKit.Core.Entites.IEntity;
using IEntityComponent = BITKit.Core.Entites.IEntityComponent;
using IEntity = BITKit.Entities.IEntity;
using IEntityComponent = BITKit.Entities.IEntityComponent;
[Serializable]
public class UnityEntitiesServiceSingleton:IEntitiesService
{

View File

@@ -22,12 +22,12 @@ namespace BITKit.Entities.Player
/// <summary>
/// 注册玩家
/// </summary>
/// <param name="entity">玩家实体</param>
void Register(Entity entity);
/// <param name="unityEntity">玩家实体</param>
void Register(Entity unityEntity);
/// <summary>
/// 注销玩家
/// </summary>
/// <param name="entity">玩家实体</param>
void UnRegister(Entity entity);
/// <param name="unityEntity">玩家实体</param>
void UnRegister(Entity unityEntity);
}
}

View File

@@ -10,7 +10,7 @@ namespace BITKit.Entities.Player
/// <summary>
/// 玩家组件的基本实现
/// </summary>
public abstract class EntityPlayerComponent : EntityComponent, IEntityPlayerComponent
public abstract class EntityPlayerBehavior : EntityBehavior, IEntityPlayerComponent
{
public virtual void OnPlayerInitialize()
{

View File

@@ -6,9 +6,8 @@ using UnityEngine;
namespace BITKit.Entities.Player
{
public class LocalPlayerComponent : EntityComponent
public class LocalPlayerBehavior : EntityBehavior
{
public override Type BaseType => typeof(LocalPlayerComponent);
private IEntityPlayerComponent[] playerComponents;
private CancellationTokenSource initializeCancellationTokenSource;
private CancellationTokenSource disposeCancellationTokenSource;
@@ -31,7 +30,7 @@ namespace BITKit.Entities.Player
{
x.OnPlayerInitialized();
}
UnityPlayerServiceService.Register((Entity)entity);
UnityPlayerServiceService.Register((Entity)UnityEntity);
}
public override async void OnDestroyComponent()
{
@@ -50,7 +49,7 @@ namespace BITKit.Entities.Player
x.OnPlayerDisposed();
}
disposeCancellationTokenSource.Dispose();
UnityPlayerServiceService.UnRegister((Entity)entity);
UnityPlayerServiceService.UnRegister((Entity)UnityEntity);
}
}
}

View File

@@ -9,7 +9,7 @@ namespace BITKit.Entities.Player
/// 基于状态机的玩家组件
/// </summary>
/// <typeparam name="T">状态,继承于<see cref="IState"/></typeparam>
public abstract class StateBasedPlayerComponent<T> : EntityPlayerComponent,IStateMachine<T> where T : IState
public abstract class StateBasedPlayerBehavior<T> : EntityPlayerBehavior,IStateMachine<T> where T : IState
{
[SerializeField] private MonoStateMachine<T> stateMachine;
public override void OnAwake()

View File

@@ -14,14 +14,14 @@ namespace BITKit.Entities.Player
public static event Action<Entity> OnPlayerInitialized;
public static event Action<Entity> OnPlayerDisposed;
public static Entity LocalPlayer { get;private set; }
public static void Register(Entity entity)
public static void Register(Entity unityEntity)
{
OnPlayerInitialized?.Invoke(entity);
LocalPlayer = entity;
OnPlayerInitialized?.Invoke(unityEntity);
LocalPlayer = unityEntity;
}
public static void UnRegister(Entity entity)
public static void UnRegister(Entity unityEntity)
{
OnPlayerDisposed?.Invoke(entity);
OnPlayerDisposed?.Invoke(unityEntity);
LocalPlayer = null;
}
Entity IPlayerService.LocalPlayer=>LocalPlayer;
@@ -35,8 +35,8 @@ namespace BITKit.Entities.Player
add => OnPlayerDisposed += value;
remove => OnPlayerDisposed -= value;
}
void IPlayerService.Register(Entity entity)=>Register(entity);
void IPlayerService.UnRegister(Entity entity)=>UnRegister(entity);
void IPlayerService.Register(Entity unityEntity)=>Register(unityEntity);
void IPlayerService.UnRegister(Entity unityEntity)=>UnRegister(unityEntity);
}
}