This commit is contained in:
CortexCore
2023-10-24 23:38:22 +08:00
parent 2c4710bc5d
commit bd40165ade
152 changed files with 3681 additions and 1531 deletions

View File

@@ -6,12 +6,12 @@ namespace BITKit.Entities
public sealed class EntityAnimator : EntityComponent
{
public Animator[] animators;
[SerializeReference, SubclassSelector] public References[] animationKeyWords;
[SerializeReference, SubclassSelector] public References _rootVelocity;
[SerializeReference, SubclassSelector] public References[] boolParameters;
[SerializeReference, SubclassSelector] public References[] floatParameters;
List<string> keyWords;
[SerializeField] private Animator[] animators;
[SerializeReference, SubclassSelector] private References[] animationKeyWords;
[SerializeReference, SubclassSelector] private References _rootVelocity;
[SerializeReference, SubclassSelector] private References[] boolParameters;
[SerializeReference, SubclassSelector] private References[] floatParameters;
private List<string> keyWords;
public override void OnAwake()
{
keyWords = animationKeyWords.Select(x => x.Get()).ToList();

View File

@@ -4,7 +4,6 @@
"references": [
"GUID:14fe60d984bf9f84eac55c6ea033a8f4",
"GUID:709caf8d7fb6ef24bbba0ab9962a3ad0",
"GUID:a45ea9d98164db34f9c3c360d07b4ab2",
"GUID:f822dbf6fdfd4a5469cccaa2e4eed3b6",
"GUID:49b49c76ee64f6b41bf28ef951cb0e50",
"GUID:7efac18f239530141802fb139776f333"

View File

@@ -62,6 +62,9 @@ namespace BITKit.Entities
/// </summary>
public interface IEntityMovement:IStateMachine<IEntityMovementState>
{
Vector3 Position { get; set; }
Quaternion Rotation { get; set; }
Vector3 Forward { get; }
/// <summary>
/// 视角中心,通常是摄像机的位置
/// </summary>

View File

@@ -6,14 +6,47 @@ using UnityEngine.InputSystem;
namespace BITKit
{
public class NavAgentMovement: StateBasedComponent<IEntityMovementState>,IEntityMovement,IHealthCallback
public class NavAgentMovement: StateBasedComponent<IEntityMovementState>,IEntityMovement
{
#region
[SerializeField] private NavMeshAgent agent;
[SerializeField] private new Rigidbody rigidbody;
[Inject] private IHealth _health;
[Inject(true)] private IEntityOverride _override;
#endregion
public override void OnStart()
{
if (_override is not null)
{
_override.OnOverride += (x) =>
{
agent.isStopped = x;
};
}
_health.OnSetAlive += OnSetAlive;
_health.OnSetHealthPoint += OnSetHP;
}
#region
public Vector3 Position
{
get=>transform.position;
set=>transform.position=value;
}
public Quaternion Rotation
{
get=>transform.rotation;
set=>transform.rotation=value;
}
public Vector3 Forward => transform.forward;
public Vector3 ViewCenter { get; set; }
public Quaternion ViewRotation { get; set; }
public Vector3 LocomotionBasedVelocity { get; private set; }
@@ -34,6 +67,9 @@ namespace BITKit
GroundVelocity = _groundVelocity;
IsGrounded = agent.isOnOffMeshLink is false;
entity.Set<bool>("IsMoving",Velocity.sqrMagnitude>=0.16f);
entity.Set<float>("SqrMagnitude",Velocity.sqrMagnitude);
if (!isDead) return;
recordPosition = rigidbody.position;

View File

@@ -0,0 +1,52 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
namespace BITKit.Entities.Movement
{
public class RigidbodyBasedMovement : StateBasedComponent<IEntityMovementState>,IEntityMovement
{
[SerializeField] private new Rigidbody rigidbody;
[SerializeField] private Animator animator;
public Vector3 Position { get; set; }
public Quaternion Rotation { get; set; }
public Vector3 Forward { get; }
public Vector3 ViewCenter { get; }
public Quaternion ViewRotation { get; }
public Vector3 LocomotionBasedVelocity { get; }
public Vector3 Velocity { get;private set; }
public Vector3 GroundVelocity { get; }
public Vector3 AngularVelocity { get; }
public bool IsGrounded { get; }
public void SyncMovement(Vector3 velocity, Vector3 position, Quaternion rotation, bool isGrounded)
{
}
public void Movement(Vector3 relativeVector)
{
}
public void Movement(InputAction.CallbackContext context)
{
}
public void ExecuteCommand<T>(T command = default)
{
}
public event Action<object> OnCommand;
public override void OnFixedUpdate(float deltaTime)
{
rigidbody.MovePosition(rigidbody.position + Velocity * deltaTime
);
}
private void OnAnimatorMove()
{
Velocity = animator.velocity;
}
}
}

View File

@@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: 08c479c2ef329e94aaac1cc920eb8ce1
guid: 9db04e8e30068ef40b2afa725bdc239d
MonoImporter:
externalObjects: {}
serializedVersion: 2

View File

@@ -1,78 +0,0 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using BITKit;
using BITKit.Animations;
using BITKit.StateMachine;
using System.Linq;
using BITFALL.Player.Equip;
using Cinemachine;
namespace BITKit.Entities
{
public interface IEquipBase : IEntryElement, IAwake, IStart, IUpdate
{
public const string _Equip = "Equip";
string AddressablePath { get; }
IEntity Entity { get; set; }
void PlayAudio(string name);
}
public abstract class BITEquipBase<T> : StateBasedMonoBehaviour<T>, IEquipBase where T : IState
{
[Header(Constant.Header.Components)]
public UnityAnimator animator;
[Header(Constant.Header.InternalVariables)]
protected IEntity entity;
public IEntity Entity { get => entity; set => entity = value; }
public virtual string AddressablePath => throw new System.NotImplementedException();
public virtual void Entry() { }
public virtual void Exit() { }
public virtual void OnAwake() {Initialize();}
public virtual void OnStart() { }
public virtual void OnUpdate(float deltaTime) { }
public virtual void PlayAudio(string eventName) { }
public virtual void EquipEvent(string eventName){}
public virtual void AnimationEvent(string eventName){}
}
[CustomType(typeof(IEquipService))]
public class EntityEquipment : EntityComponent,IEquipService
{
public EntryGroup<IEquipBase> equips = new();
public IOptional<float> Zoom { get; } = new Optional<float>(){Value = 1};
public float InitialFov;
[SerializeField] private CinemachineVirtualCamera virtualCamera;
protected IEquipBase entryComplete;
private PlayerConfig playerConfig;
public override void OnStart()
{
base.OnStart();
equips.list = GetComponentsInChildren<IEquipBase>(true).ToList();
foreach (var x in equips.list)
{
x.Entity = entity;
x.OnAwake();
}
foreach (var x in equips.list)
{
x.OnStart();
}
}
public override void OnUpdate(float deltaTime)
{
if (equips.TryGetEntried(out entryComplete))
{
entryComplete.OnUpdate(deltaTime);
}
var current = virtualCamera.m_Lens.FieldOfView;
current= Mathf.Lerp(current,Zoom.Allow ? InitialFov / Zoom.Value : PlayerConfig.Singleton.Fov , deltaTime * 5);
current = Mathf.Clamp(current, 10, PlayerConfig.Singleton.Fov);
virtualCamera.m_Lens.FieldOfView = current;
}
}
}

View File

@@ -6,17 +6,19 @@ using UnityEngine;
namespace BITKit
{
public class AutoHealComponent : EntityComponent,IHealthCallback,IDamageCallback
public class AutoHealComponent : EntityComponent,IDamageCallback
{
[SerializeField] private IntervalUpdate healDelayInterval;
[SerializeField] private IntervalUpdate healInterval;
[SerializeField] private int healIncrement;
private readonly ValidHandle allowHeal = new();
[Inject]
private IHealth _health;
public override void Initialize(IEntity _entity)
{
base.Initialize(_entity);
_entity.RegisterCallback<IHealthCallback>(this);
_health.OnSetAlive += OnSetAlive;
_health.OnSetHealthPoint += OnSetHP;
_entity.RegisterCallback<IDamageCallback>(this);
}

View File

@@ -5,13 +5,15 @@ using UnityEngine;
namespace BITKit
{
public class AutoRespawnComponent : EntityComponent,IHealthCallback,IAction
public class AutoRespawnComponent : EntityComponent,IAction
{
[SerializeField] private IntervalUpdate respawnInterval;
private bool requestRespawn;
[Inject] private IHealth _health;
public override void OnAwake()
{
entity.RegisterCallback<IHealthCallback>(this);
_health.OnSetAlive += OnSetAlive;
_health.OnSetHealthPoint += OnSetHP;
}
public override void OnUpdate(float deltaTime)

View File

@@ -61,12 +61,13 @@ namespace BITKit.Entities
}
public record DamageMessage
{
public IEntity initiator;
public IEntity target;
public int damage;
public IDamagable hit;
public Location location;
public IDamageType damageType;
public IEntity Initiator;
public IEntity Target;
public bool RawDamage;
public int Damage;
public IDamagable Hit;
public Location Location;
public IDamageType DamageType;
}
public interface IDamageCallback
{
@@ -92,13 +93,13 @@ namespace BITKit.Entities
{
while (Messages.TryDequeue(out var damageMessage))
{
var unityEntity = (Entity)damageMessage.target;
var unityEntity = (Entity)damageMessage.Target;
if (unityEntity is null || !unityEntity.TryGetComponent<IHealth>(out var heal) || !heal.IsAlive) continue;
damageMessage.initiator?.Invoke(damageMessage);
damageMessage.target?.Invoke(damageMessage);
damageMessage.Initiator?.Invoke(damageMessage);
damageMessage.Target?.Invoke(damageMessage);
foreach (var x in damageMessage.target?.GetCallbacks<IDamageCallback>()!)
foreach (var x in damageMessage.Target?.GetCallbacks<IDamageCallback>()!)
{
x.OnGetDamage(damageMessage);
}

View File

@@ -1,40 +1,12 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Contexts;
using UnityEngine;
using UnityEngine.Events;
namespace BITKit.Entities
{
public interface IHealthCallback
{
void OnSetAlive(bool alive);
void OnSetHP(int hp);
}
[Serializable]
public class UnityEventHealthCallback : IHealthCallback
{
[SerializeField] private UnityEvent<int> onSetHP;
[SerializeField] private UnityEvent onSetAlive;
[SerializeField] private UnityEvent onSetDead;
public void OnSetAlive(bool alive)
{
if (alive)
{
onSetAlive.Invoke();
}
else
{
onSetDead.Invoke();
}
}
public void OnSetHP(int hp)
{
onSetHP.Invoke(hp);
}
}
public interface IHealth
{
/// <summary>
@@ -48,7 +20,7 @@ namespace BITKit.Entities
/// <summary>
/// 当受到伤害时的回调
/// </summary>
public event Func<DamageMessage,int,int> OnDamage;
public event Func<DamageMessage,int,int> OnDamageFactory;
int HealthPoint { get; set; }
int MaxHealthPoint { get; set; }
bool IsAlive { get; }
@@ -60,13 +32,9 @@ namespace BITKit.Entities
[SerializeField] private int healthPoint = 100;
[SerializeField] private int maxHealthPoint = 100;
[Header(Constant.Header.Providers)] [SerializeField, SerializeReference, SubclassSelector]
[Obsolete]
private IHealthCallback[] additiveCallback;
public event Action<int> OnSetHealthPoint;
public event Action<bool> OnSetAlive;
public event Func<DamageMessage,int, int> OnDamage;
public event Func<DamageMessage,int, int> OnDamageFactory;
public int HealthPoint
{
@@ -99,25 +67,12 @@ namespace BITKit.Entities
{
OnSetAliveInternal(IsAlive = _isAlive);
}
foreach (var x in entity.GetCallbacks<IHealthCallback>())
{
x.OnSetHP(newHP);
}
OnSetHealthPoint?.Invoke(newHP);
}
private void OnSetAliveInternal(bool alive)
{
IsAlive = alive;
foreach (var x in entity.GetCallbacks<IHealthCallback>())
{
x.OnSetAlive(alive);
}
// foreach (var x in additiveCallback)
// {
// x.OnSetAlive(alive);
// }
OnSetAlive?.Invoke(alive);
}
@@ -128,11 +83,13 @@ namespace BITKit.Entities
private void OnGetDamage(DamageMessage damageMessage)
{
if (damageMessage.target != entity) return;
var damage = damageMessage.damage;
foreach (var x in OnDamage.CastAsFunc())
if (damageMessage.Target != entity) return;
if (IsAlive is false) return;
var damage = damageMessage.Damage;
foreach (var x in OnDamageFactory.CastAsFunc().Reverse())
{
damage = x.Invoke(damageMessage,damage);
damage = x.Invoke(damageMessage,damage);
if (damage <= 0) break;
}
AddHP(-damage);
}

View File

@@ -21,7 +21,7 @@ namespace BITKit.Entities
}
private void OnGetDamage(DamageMessage obj)
{
if (obj.target != entity) return;
if (obj.Target != entity) return;
DamageMessages.Enqueue(obj);
onGetDamage?.Invoke(obj);
foreach (var x in callbacks)

View File

@@ -12,7 +12,7 @@ namespace BITKit.Entities
{
entity.Invoke(message);
}
public Rigidbody m_rigidbody;
[SerializeField]private Rigidbody m_rigidbody;
}
}

View File

@@ -9,7 +9,8 @@
"GUID:75469ad4d38634e559750d17036d5f7c",
"GUID:d525ad6bd40672747bde77962f1c401e",
"GUID:49b49c76ee64f6b41bf28ef951cb0e50",
"GUID:508392158bd966c4d9c21e19661a441d"
"GUID:508392158bd966c4d9c21e19661a441d",
"GUID:7efac18f239530141802fb139776f333"
],
"includePlatforms": [],
"excludePlatforms": [],

View File

@@ -1,10 +1,13 @@
using System;
using BITKit.Selection;
using BITKit.Sensors;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Interactions;
namespace BITKit.Entities.Player
{
public class EntityInteractive : EntityPlayerComponent
[CustomType(typeof(ISelector))]
public class EntityInteractive : EntityPlayerComponent,ISelector
{
[Header(Constant.Header.Settings)]
[SerializeReference, SubclassSelector] private ISensor sensor;
@@ -12,9 +15,25 @@ namespace BITKit.Entities.Player
[Header(Constant.Header.InternalVariables)]
private ISelectable selected;
private IntervalUpdate cd = new(0.08f);
[Inject]
private IHealth _health;
[Inject]
private InputActionGroup _inputActionReference;
public override void OnStart()
{
_health.OnSetAlive += OnSetAlive;
}
private void OnSetAlive(bool obj)
{
TryDeSelected();
}
public override void OnUpdate(float deltaTime)
{
if (sensor.Get().TryGetAny(x=>x.TryGetComponentAny<ISelectable>(out _),out var detected))
//if (sensor.Get().TryGetAny(x=>x.TryGetComponentAny<ISelectable>(out _),out var detected))
if (sensor.Get().TryGetAny(x=>x.GetComponentInParent<ISelectable>() is not null,out var detected))
{
if (detected.TryGetComponentAny<ISelectable>(out var _detected))
{
@@ -44,34 +63,44 @@ namespace BITKit.Entities.Player
{
if (selected is null) return;
selected.SetSelectionState(SelectionState.None);
foreach (var x in entity.GetCallbacks<ISelectableCallback>())
{
x.OnInactive(selected);
}
OnInactive?.Invoke(selected);
selected = null;
}
private void Detected(ISelectable detected)
{
selected = detected;
detected.SetSelectionState(SelectionState.Hover);
foreach (var x in entity.GetCallbacks<ISelectableCallback>())
{
x.OnHover(selected);
}
OnSelected?.Invoke(selected);
}
public void Interactive(InputAction.CallbackContext context)
{
if (context.interaction is not PressInteraction || !context.performed || cd.AllowUpdate is false) return;
if (context.interaction is not PressInteraction || !context.performed ) return;
if (cd.AllowUpdate is false) return;
var _selected = selected;
if (_selected is not MonoBehaviour monoBehaviour) return;
if (monoBehaviour.TryGetComponentAny<IAction>(out var action))
{
action.Execute();
}
foreach (var x in entity.GetCallbacks<ISelectableCallback>())
{
x.OnActive(_selected);
}
selected.SetSelectionState(SelectionState.Active);
OnActive?.Invoke(selected);
}
public bool TryGetCurrentSelectable(out ISelectable selectable)
{
selectable = selected;
return selectable != null;
}
public event Action<ISelectable> OnNone;
public event Action<ISelectable> OnHover;
public event Action<ISelectable> OnActive;
public event Action<ISelectable> OnInactive;
public event Action<ISelectable> OnFocus;
public event Action<ISelectable> OnSelected;
public event Action<ISelectable> OnEnabled;
public event Action<ISelectable> OnChecked;
public event Action<ISelectable> OnRoot;
}
}

View File

@@ -1,36 +0,0 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace BITKit.Entities
{
public interface IEntityMelee
{
void Excute();
}
public class EntityMelee : EntityComponent
{
[Header(Constant.Header.Settings)]
public int damage=50;
public bool singleTarget;
public override void OnStart()
{
entity.AddListener<int>("Melee", Melee);
}
public virtual void Excute()
{
Melee(damage);
}
public virtual void AIAction(string actionName)
{
switch (actionName)
{
case "Melee":
Excute();
break;
}
}
protected virtual void Melee(int damage)
{
}
}
}

View File

@@ -8,19 +8,23 @@ using UnityEngine;
namespace BITKit.Entities
{
[CustomType(typeof(IEntityPhysics))]
public class EntityPhysics : EntityComponent,IEntityPhysics, IHealthCallback
public class EntityPhysics : EntityComponent,IEntityPhysics
{
[SerializeField] private Animator animator;
[SerializeField] private Rigidbody[] rigidbodies;
[SerializeField] private Collider[] ragdollColliders;
[SerializeField] private Joint joint;
[SerializeField] private new Rigidbody rigidbody;
private CancellationToken _cancellationToken;
[Inject]
private IHealth _health;
public override void OnAwake()
{
entity.RegisterCallback<IHealthCallback>(this);
_health.OnSetAlive += OnSetAlive;
_health.OnSetHealthPoint += OnSetHP;
_cancellationToken = entity.Get<CancellationToken>();
}
async void IHealthCallback.OnSetAlive(bool alive)
private async void OnSetAlive(bool alive)
{
IsPhysics = !alive;
if (animator)
@@ -36,6 +40,11 @@ namespace BITKit.Entities
{
}
if (alive is false && joint is not null)
{
Destroy(joint);
}
}
public void OnSetHP(int hp)

View File

@@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: de6a534eab93cbd4cacc9e47267c621b
guid: c570575d2e948724b980ea76eeca3259
folderAsset: yes
DefaultImporter:
externalObjects: {}

View File

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

View File

@@ -1,7 +1,6 @@
fileFormatVersion: 2
guid: 3614fcbb2ebe14e418eadf82d1c67870
folderAsset: yes
DefaultImporter:
guid: e4e97feeabe888f4a8134328a497d6fa
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:

View File

@@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: 632d0b190624f7f46971923e4fedffcb
guid: bd5ade15e3c249d4da89ea45637eaefb
folderAsset: yes
DefaultImporter:
externalObjects: {}

View File

@@ -0,0 +1,16 @@
{
"name": "BITKit.Entities.Slot",
"rootNamespace": "",
"references": [
"GUID:14fe60d984bf9f84eac55c6ea033a8f4"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": true
}

View File

@@ -1,7 +1,6 @@
fileFormatVersion: 2
guid: e8173f883ff93344db922487c65da5fa
folderAsset: yes
DefaultImporter:
guid: f32d23892f67f544299b53ae07475659
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:

View File

@@ -0,0 +1,10 @@
using System.Collections;
using System.Collections.Generic;
namespace BITKit.Entities.Slot
{
public interface IEntitySlot<T> where T : class
{
IDictionary<string,T> Slots { get; }
}
}

View File

@@ -1,5 +1,5 @@
fileFormatVersion: 2
guid: d61f8d5d7b83b1941831e20da974aa54
guid: 6e62578e406f81744b5c6aad418e8783
MonoImporter:
externalObjects: {}
serializedVersion: 2

View File

@@ -0,0 +1,15 @@
using System.Collections;
using System.Collections.Generic;
using AYellowpaper.SerializedCollections;
using UnityEngine;
namespace BITKit.Entities.Slot
{
[CustomType(typeof(IEntitySlot<Transform>))]
public sealed class UnityEntitySlot : EntityComponent, IEntitySlot<Transform>
{
[SerializeField] private SerializedDictionary<string,Transform> dictionary = new();
public IDictionary<string, Transform> Slots => dictionary;
}
}

View File

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

View File

@@ -28,10 +28,48 @@ namespace BITKit.Entities
}
IServiceProvider Core.Entites.IEntity.ServiceProvider=> throw new InvalidOperationException("Unity Entity can't register component");
public void Inject(object obj)
{
foreach (var fieldInfo in obj
.GetType()
.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.Where(fieldInfo=>fieldInfo.GetCustomAttribute<InjectAttribute>() is not null))
{
var type = fieldInfo.FieldType;
var attribute = fieldInfo.GetCustomAttribute<InjectAttribute>();
var currentValue = fieldInfo.GetValue(obj);
try
{
switch (currentValue)
{
case null:
break;
case Core.Entites.IEntityComponent entityComponent:
if(entityComponent.Entity.Id == Id)
continue;
break;
case MonoBehaviour { destroyCancellationToken: { IsCancellationRequested: false } }:
continue;
case not null:
continue;
}
}
catch (MissingReferenceException){}
if(genericEvent.TryGetObjectDirect(type.FullName,out var value))
{
fieldInfo.SetValue(obj,value);
}
else if(attribute?.CanBeNull is false)
{
BIT4Log.Warning<Entity>($"{name}未找到{type.FullName}");
BIT4Log.Warning<Entity>(genericEvent.GetDiagnostics());
}
}
}
private CancellationToken _cancellationToken;
private bool isInitialized;
private Core.Entites.IEntityComponent[] _components => entityComponents;
private Core.Entites.IEntityComponent[] _components => entityComponents.Cast<Core.Entites.IEntityComponent>().ToArray();
private void Awake()
{
@@ -44,39 +82,41 @@ namespace BITKit.Entities
}
private void Start()
{
foreach (var x in entityComponents)
try
{
foreach (var att in x.GetType().GetCustomAttributes<CustomTypeAttribute>())
var monoBehaviours = GetComponentsInChildren<MonoBehaviour>(true);
foreach (var x in monoBehaviours)
{
genericEvent.Set(att.Type,x);
genericEvent.Set(att.Type.FullName, x);
genericEvent.SetDirect(att.Type.FullName,x);
foreach (var att in x
//.GetCustomAttributes<CustomTypeAttribute>()
.GetType()
//.GetCustomAttributes<CustomTypeAttribute>()
.GetCustomAttributes()
.OfType<CustomTypeAttribute>()
)
{
genericEvent.Set(att.Type,x);
genericEvent.Set(att.Type.FullName, x);
genericEvent.SetDirect(att.Type.FullName,x);
}
genericEvent.Set(x.GetType(),x);
}
}
foreach (var x in GetComponentsInChildren<MonoBehaviour>(true))
{
foreach (var fieldInfo in x
.GetType()
.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.Where(fieldInfo=>fieldInfo.GetCustomAttribute<InjectAttribute>() is not null))
foreach (var x in monoBehaviours)
{
var type = fieldInfo.FieldType;
if(genericEvent.TryGetObjectDirect(type.FullName,out var value))
{
fieldInfo.SetValue(x,value);
}
else
{
BIT4Log.Warning<Entity>($"{name}未找到{type.FullName}");
BIT4Log.Warning<Entity>(genericEvent.GetDiagnostics());
}
Inject(x);
}
}
entityComponents.ForEach(x => x.Initialize(this));
entityComponents.ForEach(x => x.Initialize(this));
entityComponents.ForEach(x => x.OnAwake());
entityComponents.ForEach(x => x.OnStart());
isInitialized = true;
entityComponents.ForEach(x => x.OnAwake());
entityComponents.ForEach(x => x.OnStart());
isInitialized = true;
}
catch (Exception e)
{
Debug.LogWarning(name);
Debug.LogException(e);
}
}
private void OnDestroy()
{

View File

@@ -18,8 +18,14 @@ namespace BITKit.Entities
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) { entity = _entity; }
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) { }

View File

@@ -9,17 +9,22 @@ namespace BITKit.Entities
bool IsOvering { get; }
void AddOverride(object key);
void RemoveOverride(object key);
event Action<bool> OnOverride;
}
public interface IEntityOverrideCallback
{
void OnEntryOverride(bool @override);
}
[CustomType(typeof(IEntityOverride))]
public class EntityOverride : EntityComponent,IEntityOverride
{
[SerializeField,ReadOnly] private bool isOvering;
public bool IsOvering => _allowOverrideHandle;
private readonly ValidHandle _allowOverrideHandle = new();
public void AddOverride(object key) => _allowOverrideHandle.AddElement(key);
public void RemoveOverride(object key)=>_allowOverrideHandle.RemoveElement(key);
public event Action<bool> OnOverride;
public override void Initialize(IEntity _entity)
{
base.Initialize(_entity);
@@ -32,10 +37,8 @@ namespace BITKit.Entities
}
private void Override(bool @override)
{
foreach (var x in entity.GetCallbacks<IEntityOverrideCallback>())
{
x.OnEntryOverride(@override);
}
OnOverride?.Invoke(@override);
isOvering=@override;
}
}
}

View File

@@ -12,11 +12,12 @@ namespace BITKit.Entities.Player
public abstract class StateBasedPlayerComponent<T> : EntityPlayerComponent,IStateMachine<T> where T : IState
{
[SerializeField] private MonoStateMachine<T> stateMachine;
public override void Initialize(IEntity _entity)
public override void OnAwake()
{
base.Initialize(_entity);
stateMachine?.Initialize();
base.OnAwake();
}
public bool Enabled
{
get => stateMachine.Enabled;