BITKit/Packages/Runtime~/Unity/Extensions/Netcode/EntityNet.cs

70 lines
3.1 KiB
C#
Raw Normal View History

2023-06-05 19:57:17 +08:00
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.VisualScripting;
using UnityEngine.Events;
using System.Linq;
using Unity.Netcode;
namespace BITKit.Entities
{
public class EntityNet : NetworkBehaviour, IEntity
{
GenericEvent genericEvent = new();
Processor processor = new();
public IEntityComponent[] entityComponents { get; set; }
protected virtual void Awake()
{
entityComponents = GetComponentsInChildren<IEntityComponent>(true);
entityComponents.ForEach(x => x.Initialize(this));
}
protected virtual void Start()
{
entityComponents.ForEach(x => x.OnAwake());
entityComponents.ForEach(x => x.OnStart());
}
public override void OnDestroy()
{
base.OnDestroy();
entityComponents.ForEach(x => x.OnDestroyComponent());
}
protected virtual void Update()
{
entityComponents.ForEach(x => x.OnUpdate(Time.deltaTime));
}
protected virtual void FixedUpdate()
{
entityComponents.ForEach(x => x.OnFixedUpdate(Time.fixedDeltaTime));
}
protected virtual void LateUpdate()
{
entityComponents.ForEach(x => x.OnLateUpdate(Time.deltaTime));
}
public override void OnNetworkSpawn()
{
Set<bool>(nameof(EntityComponent.isLocalPlayer), IsLocalPlayer);
IEntity.LocalPlayer = this;
entityComponents.ForEach(x => x.OnSpawn());
}
public override void OnNetworkDespawn()
{
entityComponents.ForEach(x => x.OnDespawn());
IEntity.LocalPlayer = null;
}
public void AddListener<T>(Action<T> action) => genericEvent.AddListener<T>(action);
public void Invoke<T>(T value) => genericEvent.Invoke<T>(value);
public void RemoveListener<T>(Action<T> action) => genericEvent.RemoveListener<T>(action);
public void AddListener<T>(string key, Action<T> action) => genericEvent.AddListener<T>(key, action);
public void Invoke<T>(string key, T value) => genericEvent.Invoke<T>(key, value);
public void RemoveListener<T>(string key, Action<T> action) => genericEvent.RemoveListener<T>(key, action);
public T Get<T>(string key = default) => genericEvent.Get<T>(key) ?? GetComponent<T>();
public void Set<T>(T value) => genericEvent.Set<T>(value);
public void Set<T>(string key, T value) => 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);
}
}