From 5b7c8fcb88c841aa0e0550875056c4655ffb48e2 Mon Sep 17 00:00:00 2001 From: Tore Bergebakken Date: Sun, 20 Apr 2025 00:15:22 +0200 Subject: [PATCH 1/3] wip --- Assets/RicochetModifier.cs | 6 +- Assets/Scripts/Augment/Augment.cs | 4 + .../AugmentImplementations/AmmoBoxBody.cs | 18 ++--- .../Augment/AugmentImplementations/DDRBody.cs | 75 ++++++++++--------- .../AugmentImplementations/DynamiteBarrel.cs | 20 +---- .../Augment/AugmentImplementations/Fire.cs | 35 +++++---- .../HackingExtension.cs | 14 ++-- .../AugmentImplementations/LawnMower.cs | 23 +++--- .../Augment/AugmentImplementations/Pan.cs | 33 ++++---- .../AugmentImplementations/Revolver.cs | 26 +++---- .../AugmentImplementations/RopeBody.cs | 47 +++++++----- .../AugmentImplementations/RubberSniper.cs | 10 +-- .../AugmentImplementations/SateliteUplink.cs | 35 ++++----- .../AugmentImplementations/Solar/SolarBody.cs | 17 ++++- .../AugmentImplementations/Telescope.cs | 30 +++----- .../Augment/BulletModifiers/DecalModifier.cs | 7 +- .../InheritMomentumModifier.cs | 16 ++-- .../KnockbackOnShotModifier.cs | 7 +- .../Augment/BulletModifiers/RecoilModifier.cs | 7 +- .../StickyProjectileModifier.cs | 12 +-- Assets/Scripts/Augment/GunBarrel.cs | 9 ++- Assets/Scripts/Augment/GunBody.cs | 21 ++++-- Assets/Scripts/Augment/GunExtension.cs | 17 +++++ Assets/Scripts/Augment/GunFactory.cs | 2 + Assets/Scripts/Augment/PlayerHand.cs | 11 +-- Assets/Scripts/Augment/ProjectileModifier.cs | 5 +- .../PortalExtensionController.cs | 30 +++----- Assets/Scripts/Gamestate/PlayerManager.cs | 29 +++---- Assets/Scripts/Gamestate/PlayerSubscriber.cs | 5 ++ Assets/Scripts/UI/PlayerHUDController.cs | 12 ++- Assets/Scripts/Utils/ObjectPool.cs | 5 +- Assets/SodiePopper.cs | 19 +++-- 32 files changed, 323 insertions(+), 284 deletions(-) create mode 100644 Assets/Scripts/Gamestate/PlayerSubscriber.cs diff --git a/Assets/RicochetModifier.cs b/Assets/RicochetModifier.cs index f31221db9..e0083a6b6 100644 --- a/Assets/RicochetModifier.cs +++ b/Assets/RicochetModifier.cs @@ -2,17 +2,17 @@ public class RicochetModifier : MonoBehaviour, ProjectileModifier { - public void ricochetProjectile(RaycastHit other, ref ProjectileState state) + public void RicochetProjectile(RaycastHit other, ref ProjectileState state) { state.direction = Vector3.Reflect(state.direction, other.normal); } public void Attach(ProjectileController projectile) { - projectile.OnColliderHit += ricochetProjectile; + projectile.OnColliderHit += RicochetProjectile; } public void Detach(ProjectileController projectile) { - projectile.OnColliderHit -= ricochetProjectile; + projectile.OnColliderHit -= RicochetProjectile; } } diff --git a/Assets/Scripts/Augment/Augment.cs b/Assets/Scripts/Augment/Augment.cs index f4bdae973..8015a942c 100644 --- a/Assets/Scripts/Augment/Augment.cs +++ b/Assets/Scripts/Augment/Augment.cs @@ -23,6 +23,10 @@ public abstract class Augment : NetworkBehaviour // For displaying items with correct alignment public Transform midpoint; + public abstract void Attach(GunController gunController); + + public abstract void Detach(GunController gunController); + public virtual void BuildStats(GunStats gunStats) { foreach (var modifier in statModifiers) diff --git a/Assets/Scripts/Augment/AugmentImplementations/AmmoBoxBody.cs b/Assets/Scripts/Augment/AugmentImplementations/AmmoBoxBody.cs index 5cd9823d5..2d82742f3 100644 --- a/Assets/Scripts/Augment/AugmentImplementations/AmmoBoxBody.cs +++ b/Assets/Scripts/Augment/AugmentImplementations/AmmoBoxBody.cs @@ -15,25 +15,25 @@ public class AmmoBoxBody : GunBody [SerializeField] private PlayerHand playerHandRight; - public override void Start() + public override void Attach(GunController gunController) { - gunController = transform.parent.GetComponent(); - if (!gunController) - return; gunController.onFireStart += Reload; StartCoroutine(SetClosestAmmoBox()); if (!gunController.Player) return; - playerHandRight.SetPlayer(gunController.Player); + playerHandRight.Subscribe(gunController.Player); playerHandRight.gameObject.SetActive(true); - playerHandLeft.SetPlayer(gunController.Player); + playerHandLeft.Subscribe(gunController.Player); playerHandLeft.gameObject.SetActive(true); } - private void OnDestroy() + public override void Detach(GunController gunController) { - if (gunController) - gunController.onFireStart -= Reload; + gunController.onFireStart -= Reload; + if (!gunController.Player) + return; + playerHandRight.Unsubscribe(gunController.Player); + playerHandLeft.Unsubscribe(gunController.Player); } private IEnumerator SetClosestAmmoBox() diff --git a/Assets/Scripts/Augment/AugmentImplementations/DDRBody.cs b/Assets/Scripts/Augment/AugmentImplementations/DDRBody.cs index dc510feb0..9a7017887 100644 --- a/Assets/Scripts/Augment/AugmentImplementations/DDRBody.cs +++ b/Assets/Scripts/Augment/AugmentImplementations/DDRBody.cs @@ -71,53 +71,65 @@ public class DDRBody : GunBody private AudioSource audioSource; private InputManager inputManager; - public override void Start() + private void Start() { meshRenderer.materials[screenMaterialIndex] = Instantiate(meshRenderer.materials[screenMaterialIndex]); ddrMaterial = meshRenderer.materials[screenMaterialIndex]; precisionText.enabled = false; + } + public override void Attach(GunController gunController) + { musicPace = 60f / MusicTrackManager.Singleton.BeatsPerMinute; var secondsPerArrow = MusicTrackManager.Singleton.BeatsPerBar * musicPace; secondsPerUnitHeight = secondsPerArrow / (targetHeight - startHeight); - gunController = transform.parent.GetComponent(); - if (!gunController) + if (!(gunController.Player && gunController.Player.inputManager)) return; + inputManager = gunController.Player.inputManager; + inputManager.onFirePerformed += Fire; + inputManager.onMovePerformed += ArrowSelect; - if (gunController.Player && gunController.Player.inputManager) - { - inputManager = gunController.Player.inputManager; - inputManager.onFirePerformed += Fire; - inputManager.onMovePerformed += ArrowSelect; + var delay = (float)(MusicTrackManager.Singleton.IsfadingOutPreviousTrack + ? MusicTrackManager.Singleton.TrackOffset + : secondsPerArrow - (MusicTrackManager.Singleton.TimeSinceTrackStart % secondsPerArrow)); - var delay = (float)(MusicTrackManager.Singleton.IsfadingOutPreviousTrack - ? MusicTrackManager.Singleton.TrackOffset - : secondsPerArrow - (MusicTrackManager.Singleton.TimeSinceTrackStart % secondsPerArrow)); + PickNewTargetDirection(); + + arrowMoverTween = LeanTween.value(gameObject, SetArrowHeigth, startHeight, screenHeight, secondsPerUnitHeight * (screenHeight - startHeight)) + .setDelay(delay) + .setRepeat(-1).id; - PickNewTargetDirection(); + screenPulseAnimatorTween = LeanTween.value(gameObject, SetBackgroundZoom, 0.5f, 1.5f, musicPace) + .setDelay(delay) + .setLoopPingPong() + .setOnComplete( + () => animator.OnFire(gunController.stats)).id; - arrowMoverTween = LeanTween.value(gameObject, SetArrowHeigth, startHeight, screenHeight, secondsPerUnitHeight * (screenHeight - startHeight)) - .setDelay(delay) - .setRepeat(-1).id; + animator.OnInitialize(gunController.stats); - screenPulseAnimatorTween = LeanTween.value(gameObject, SetBackgroundZoom, 0.5f, 1.5f, musicPace) - .setDelay(delay) - .setLoopPingPong() - .setOnComplete( - () => animator.OnFire(gunController.stats)).id; + playerHandLeft.Subscribe(gunController.Player); + playerHandLeft.gameObject.SetActive(true); + playerHandRight.Subscribe(gunController.Player); + playerHandRight.gameObject.SetActive(true); - animator.OnInitialize(gunController.stats); + audioSource = GetComponent(); + } - playerHandLeft.SetPlayer(gunController.Player); - playerHandLeft.gameObject.SetActive(true); - playerHandRight.SetPlayer(gunController.Player); - playerHandRight.gameObject.SetActive(true); + public override void Detach(GunController gunController) + { + if (!gunController.Player) + return; + playerHandRight.Unsubscribe(gunController.Player); + playerHandLeft.Unsubscribe(gunController.Player); - audioSource = GetComponent(); - } + if (!inputManager) + return; + inputManager.onFirePerformed -= Fire; + inputManager.onMovePerformed -= ArrowSelect; } + private void Update() { if (!inputManager) @@ -326,13 +338,4 @@ private void PickNewTargetDirection() arrowDirection = (ArrowDirection)Random.Range(0, 4); AnimateTargetArrowRotation(oldDirection, arrowDirection); } - - private void OnDestroy() - { - if (!inputManager) - return; - - inputManager.onFirePerformed -= Fire; - inputManager.onMovePerformed -= ArrowSelect; - } } diff --git a/Assets/Scripts/Augment/AugmentImplementations/DynamiteBarrel.cs b/Assets/Scripts/Augment/AugmentImplementations/DynamiteBarrel.cs index a6d0366ab..57f43b3d0 100644 --- a/Assets/Scripts/Augment/AugmentImplementations/DynamiteBarrel.cs +++ b/Assets/Scripts/Augment/AugmentImplementations/DynamiteBarrel.cs @@ -3,7 +3,6 @@ using System.Collections; using System.Collections.Generic; using System.Linq; -using Unity.VisualScripting; using UnityEngine; using UnityEngine.InputSystem; @@ -22,9 +21,8 @@ public class DynamiteBarrel : GunBarrel // TODO: allow for even more by instantiating particles with a positionbuffer instead private const int maxDetonatableInTotal = 10; - void Start() + public override void Attach(GunController gunController) { - gunController = transform.parent.GetComponent(); if (!gunController || !gunController.Player) return; @@ -123,22 +121,10 @@ private void RpcDetonate() private void OnDeath(PlayerManager killer, PlayerManager victim, DamageInfo info) { - StopAllCoroutines(); - if (!gunController || !gunController.Player) - return; - - activeDynamites.ForEach(dynamite => dynamite.gameObject.SetActive(false)); - - stickyModifer.OnStuckToTarget -= AddDynamite; - - if (gunController.Player is not AIManager && gunController.Player.inputManager) - { - gunController.Player.inputManager.onZoomPerformed -= OnZoom; - gunController.Player.GetComponent().ReEnableZoom(); - } + Detach(gunController); } - private void OnDestroy() + public override void Detach(GunController gunController) { StopAllCoroutines(); if (!gunController || !gunController.Player || !gunController.Player.IsAlive) diff --git a/Assets/Scripts/Augment/AugmentImplementations/Fire.cs b/Assets/Scripts/Augment/AugmentImplementations/Fire.cs index abd68c0b5..12d32b514 100644 --- a/Assets/Scripts/Augment/AugmentImplementations/Fire.cs +++ b/Assets/Scripts/Augment/AugmentImplementations/Fire.cs @@ -19,7 +19,6 @@ public class Fire : GunExtension private StuckObject stuckFirePrefab; [SerializeField] private LayerMask trailLayers; - private GunController gunController; private AudioSource audioSource; [SerializeField] private AudioGroup lighterSound; @@ -39,14 +38,13 @@ public class Fire : GunExtension [SerializeField] private StickyProjectileModifier stickyModifier; - private HashSet trackedProjectiles = new HashSet(); + private HashSet trackedProjectiles = new(); // Used to keep track of the healthControllers currently burning - public HashSet hitHealthControllers = new HashSet(); + public HashSet hitHealthControllers = new(); - void Awake() + public override void Attach(GunController gunController) { audioSource = GetComponent(); - gunController = transform.parent.GetComponent(); if (!gunController) return; @@ -64,18 +62,35 @@ void Awake() stickyModifier.OnStuckToTarget += InitializeFlame; projectileType = ProjectileType.Mesh; } - else if (gunController.projectile is BulletController) + else if (gunController.projectile is BulletController controller) { - ((BulletController)gunController.projectile).SetTrail(fireTrail); + controller.SetTrail(fireTrail); projectileType = ProjectileType.Hitscan; } else if (gunController.projectile is LazurController) { projectileType = ProjectileType.Laser; } + } + + public override void Detach(GunController gunController) + { + stuckFirePool?.Flush(); + positionActiveBuffer?.Dispose(); + + if (!gunController) + return; + gunController.onInitializeGun -= AddFireToProjectile; + gunController.onFireEnd -= PlayShotAudio; + gunController.projectile.OnProjectileInit -= TrackProjectile; + gunController.projectile.UpdateProjectileMovement -= ApplyTrails; + + if (gunController.projectile is MeshProjectileController) + stickyModifier.OnStuckToTarget -= InitializeFlame; } + private void TrackProjectile(ref ProjectileState state, GunStats stats) { trackedProjectiles.Add(state); @@ -206,12 +221,6 @@ private void PlayShotAudio(GunStats stats) lighterSound.Play(audioSource); } - private void OnDestroy() - { - stuckFirePool?.Flush(); - positionActiveBuffer?.Dispose(); - } - #if UNITY_EDITOR private void OnDrawGizmos() { diff --git a/Assets/Scripts/Augment/AugmentImplementations/HackingExtension.cs b/Assets/Scripts/Augment/AugmentImplementations/HackingExtension.cs index a6700b6f4..1a8413fb7 100644 --- a/Assets/Scripts/Augment/AugmentImplementations/HackingExtension.cs +++ b/Assets/Scripts/Augment/AugmentImplementations/HackingExtension.cs @@ -10,18 +10,22 @@ public class HackingExtension : GunExtension private float scrollAmount = 0.10f; private const int hackingScreenMaterialIndex = 1; - private GunController gunController; - private void Start() { meshRenderer.materials[hackingScreenMaterialIndex] = Instantiate(meshRenderer.materials[hackingScreenMaterialIndex]); hackingScreen = meshRenderer.materials[hackingScreenMaterialIndex]; - gunController = transform.parent.GetComponent(); - if (!gunController) - return; + } + + public override void Attach(GunController gunController) + { gunController.onFireStart += Fire; } + public override void Detach(GunController gunController) + { + gunController.onFireStart -= Fire; + } + private void Fire(GunStats stats) { hackingScreen.SetFloat("_ScrollAmount", hackingScreen.GetFloat("_ScrollAmount") + scrollAmount); diff --git a/Assets/Scripts/Augment/AugmentImplementations/LawnMower.cs b/Assets/Scripts/Augment/AugmentImplementations/LawnMower.cs index 4ef70d571..2c0d23591 100644 --- a/Assets/Scripts/Augment/AugmentImplementations/LawnMower.cs +++ b/Assets/Scripts/Augment/AugmentImplementations/LawnMower.cs @@ -49,13 +49,14 @@ public class LawnMower : GunBody [SerializeField] private AudioGroup overheatSounds; - public override void Start() + private void Start() { meshRenderer.materials[mowerScreenMaterialIndex] = Instantiate(meshRenderer.materials[mowerScreenMaterialIndex]); mowerScreen = meshRenderer.materials[mowerScreenMaterialIndex]; - gunController = transform.parent.GetComponent(); - if (!gunController) - return; + } + + public override void Attach(GunController gunController) + { gunController.onFireStart += Fire; gunController.onFireEnd += FireEnd; @@ -66,9 +67,9 @@ public override void Start() return; audioSource = GetComponent(); playerHandLeft.gameObject.SetActive(true); - playerHandLeft.SetPlayer(gunController.Player); + playerHandLeft.Subscribe(gunController.Player); playerHandRight.gameObject.SetActive(true); - playerHandRight.SetPlayer(gunController.Player); + playerHandRight.Subscribe(gunController.Player); handAnimator = GetComponent(); LineHoldingPoint = playerHandLeft.HoldingPoint; handString.gameObject.SetActive(true); @@ -77,14 +78,18 @@ public override void Start() gunControllerDisplay.GetComponentInChildren().LineHoldingPoint = gunController.Player.PlayerIK.LeftHandIKTransform; } - private void OnDestroy() + public override void Detach(GunController gunController) { if (MatchController.Singleton) MatchController.Singleton.onRoundEnd -= DisableLine; - if (!gunController) - return; + gunController.onFireStart -= Fire; gunController.onFireEnd -= FireEnd; + + if (!gunController.Player) + return; + playerHandRight.Unsubscribe(gunController.Player); + playerHandLeft.Unsubscribe(gunController.Player); } private void LateUpdate() diff --git a/Assets/Scripts/Augment/AugmentImplementations/Pan.cs b/Assets/Scripts/Augment/AugmentImplementations/Pan.cs index bb43a3fc4..91aa4859f 100644 --- a/Assets/Scripts/Augment/AugmentImplementations/Pan.cs +++ b/Assets/Scripts/Augment/AugmentImplementations/Pan.cs @@ -1,5 +1,3 @@ -using System.Collections; -using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.InputSystem; @@ -15,12 +13,11 @@ public class Pan : GunExtension private PlayerMovement playerMovement; private const float skateJumpForce = 11f; private const float skateMoveForce = 2f; - private GunController gunController; private const int hitBoxLayer = 3; private const int aiExplosionLayer = 15; - void Start() + + public override void Attach(GunController gunController) { - gunController = transform.parent.GetComponent(); if (!gunController) return; if (!gunController.Player) @@ -31,7 +28,7 @@ void Start() return; } panModel.localScale = new Vector3(2.5f, 2.5f, 2.5f); - panModel.localPosition = new Vector3(panModel.localPosition.x, panModel.localPosition.y -0.3f, panModel.localPosition.z); + panModel.localPosition = new Vector3(panModel.localPosition.x, panModel.localPosition.y - 0.3f, panModel.localPosition.z); var health = gunController.Player.GetComponent(); if (gunController.Player is AIManager) @@ -52,11 +49,21 @@ void Start() hitboxCollider.enabled = false; playerMovement = gunController.Player.GetComponent(); gunController.Player.GunOrigin.GetComponentsInChildren() - .ToList().ForEach(box => box.health = health); + .ToList().ForEach(box => box.health = health); if (playerMovement) playerMovement.OnMove += TryPanSkateBoost; } + public override void Detach(GunController gunController) + { + if (!gunController.Player) + return; + if (gunController.Player.inputManager) + gunController.Player.inputManager.onSelect -= TryTrickJump; + if (playerMovement) + playerMovement.OnMove -= TryPanSkateBoost; + } + private void TryTrickJump(InputAction.CallbackContext ctx) { bool isCorrectMovement = playerMovement && playerMovement.StateIsAir && playerMovement.IsCrouching; @@ -69,19 +76,11 @@ private void TryTrickJump(InputAction.CallbackContext ctx) private void TryPanSkateBoost(Rigidbody body) { - bool isSkating = (playerMovement.StateIsAir && playerMovement.IsCrouching && Mathf.Abs(body.velocity.y) < 0.01f); - bool isMoving = (gunController.Player.inputManager.moveInput.magnitude > 0.5f); + bool isSkating = playerMovement.StateIsAir && playerMovement.IsCrouching && Mathf.Abs(body.velocity.y) < 0.01f; + bool isMoving = gunController.Player.inputManager.moveInput.magnitude > 0.5f; if (!isMoving || !isSkating) return; Vector3 moveDirection = gunController.Player.transform.forward * gunController.Player.inputManager.moveInput.y + gunController.Player.transform.right * gunController.Player.inputManager.moveInput.x; body.AddForce(moveDirection * skateMoveForce, ForceMode.VelocityChange); } - private void OnDestroy() - { - if (gunController) - if (gunController.Player) - if (gunController.Player.inputManager) - gunController.Player.inputManager.onSelect -= TryTrickJump; - } - } diff --git a/Assets/Scripts/Augment/AugmentImplementations/Revolver.cs b/Assets/Scripts/Augment/AugmentImplementations/Revolver.cs index 28f53c10e..3a0fbbd6f 100644 --- a/Assets/Scripts/Augment/AugmentImplementations/Revolver.cs +++ b/Assets/Scripts/Augment/AugmentImplementations/Revolver.cs @@ -23,21 +23,28 @@ public class Revolver : GunBody private bool isReloadInProgress = false; - public override void Start() + public override void Attach(GunController gunController) { audioSource = GetComponent(); - gunController = transform.parent.GetComponent(); - if (!gunController) - return; gunController.onFireEnd += Reload; if (!gunController.Player) return; - playerHandLeft.SetPlayer(gunController.Player); - playerHandRight.SetPlayer(gunController.Player); + playerHandLeft.Subscribe(gunController.Player); + playerHandRight.Subscribe(gunController.Player); playerHandRight.gameObject.SetActive(true); } + public override void Detach(GunController gunController) + { + gunController.onFireEnd -= Reload; + + if (!gunController.Player) + return; + playerHandRight.Unsubscribe(gunController.Player); + playerHandLeft.Unsubscribe(gunController.Player); + } + protected override void Reload(GunStats stats) { if (gunController.stats.Ammo > 0 || isReloadInProgress) @@ -96,11 +103,4 @@ public void ResetReload() gunController.Reload(reloadEfficiencyPercentage); isReloadInProgress = false; } - - private void OnDestroy() - { - if (gunController) - gunController.onFireEnd -= Reload; - } - } diff --git a/Assets/Scripts/Augment/AugmentImplementations/RopeBody.cs b/Assets/Scripts/Augment/AugmentImplementations/RopeBody.cs index 0a960d111..d123c1f81 100644 --- a/Assets/Scripts/Augment/AugmentImplementations/RopeBody.cs +++ b/Assets/Scripts/Augment/AugmentImplementations/RopeBody.cs @@ -48,15 +48,18 @@ public class RopeBody : GunBody private int throwTween; - public override void Start() + private void Start() { - base.Start(); - gunController = transform.parent.GetComponent(); if (!gunController || !gunController.Player) { rope.enabled = false; - return; } + } + + public override void Attach(GunController gunController) + { + if (!gunController.Player) + return; rope.Line.gameObject.layer = 0; rope.Target = ropeTarget; plugAnchor = Instantiate(plugAnchorPrefab); @@ -65,9 +68,9 @@ public override void Start() rope.ResetRope(plugAnchor.WireOrigin); plugAnchor.Health.onDeath += RemoveRope; playerBody = gunController.Player.GetComponent(); - playerHandRight.SetPlayer(gunController.Player); + playerHandRight.Subscribe(gunController.Player); playerHandRight.gameObject.SetActive(true); - playerHandLeft.SetPlayer(gunController.Player); + playerHandLeft.Subscribe(gunController.Player); playerHandLeft.gameObject.SetActive(true); gunController.onFireNoAmmo += TryThrowPlug; movement = gunController.Player.GetComponent(); @@ -76,6 +79,26 @@ public override void Start() gunController.stats.Ammo = 0; } + public override void Detach(GunController gunController) + { + if (!plugAnchor) + return; + plugAnchor.Health.onDeath -= RemoveRope; + gunController.onFireNoAmmo -= TryThrowPlug; + + if (!gunController.Player) + return; + playerHandRight.Unsubscribe(gunController.Player); + playerHandLeft.Unsubscribe(gunController.Player); + } + + protected override void OnDestroy() + { + base.OnDestroy(); + Destroy(plugAnchor); + } + + private void PullingWire() { if (!isWired || isThrowing || canThrow) @@ -348,16 +371,4 @@ private void Update() for (int i = 0; i < coils.Length; i++) coils[i].SetActive(i > cutOffIndex); } - - private void OnDestroy() - { - if (!plugAnchor) - return; - plugAnchor.Health.onDeath -= RemoveRope; - Destroy(plugAnchor); - if (!gunController) - return; - gunController.onFireNoAmmo -= TryThrowPlug; - } - } diff --git a/Assets/Scripts/Augment/AugmentImplementations/RubberSniper.cs b/Assets/Scripts/Augment/AugmentImplementations/RubberSniper.cs index 88b76df6d..1bfa8e3da 100644 --- a/Assets/Scripts/Augment/AugmentImplementations/RubberSniper.cs +++ b/Assets/Scripts/Augment/AugmentImplementations/RubberSniper.cs @@ -9,12 +9,8 @@ public class RubberSniper : GunExtension [SerializeField] private float maxHitDistance = 100f; - private GunController gunController; - private void Awake() + public override void Attach(GunController gunController) { - gunController = transform.parent.GetComponent(); - if (!gunController) - return; gunController.onFire += Fire; if (!gunController.Player) return; @@ -24,10 +20,8 @@ private void Awake() gunController.onFire += Aim; } - private void OnDestroy() + public override void Detach(GunController gunController) { - if (!gunController) - return; gunController.onFire -= Fire; if (!gunController.Player) return; diff --git a/Assets/Scripts/Augment/AugmentImplementations/SateliteUplink.cs b/Assets/Scripts/Augment/AugmentImplementations/SateliteUplink.cs index 458b47f4c..71b32dbe1 100644 --- a/Assets/Scripts/Augment/AugmentImplementations/SateliteUplink.cs +++ b/Assets/Scripts/Augment/AugmentImplementations/SateliteUplink.cs @@ -56,18 +56,8 @@ public class SateliteUplink : NetworkBehaviour, ProjectileModifier private void Start() { - gunController = transform.parent.GetComponent(); - if (!gunController) - return; - - gunController.onFireStart += StartTracking; - - garbageParent = new GameObject().transform; - garbageParent.gameObject.name = "TrashUplinkGarbageHolder"; - - timer = GetComponent(); - timer.OnTimerRunCompleted += OnCooldownEnd; - timer.StartTimer(cooldown); + // TODO should this one get destroyed??? + garbageParent = new GameObject("TrashUplinkGarbageHolder").transform; if (isServer) { @@ -79,7 +69,6 @@ private void Start() private void SeedRandom(int seed) { random = new System.Random(seed); - } private FallingHazard PickTemplate() @@ -113,6 +102,13 @@ private void StartTracking(GunStats stats) public void Attach(ProjectileController projectile) { + gunController = projectile.GunController; + gunController.onFireStart += StartTracking; + + timer = GetComponent(); + timer.OnTimerRunCompleted += OnCooldownEnd; + timer.StartTimer(cooldown); + garbagePool = new ObjectPool(PickTemplate, maxGarbagePresent); targetingReticlePool = new ObjectPool(targetingReticle, maxLaunchesPerShot); projectile.OnProjectileInit += Track; @@ -122,13 +118,11 @@ public void Attach(ProjectileController projectile) public void Detach(ProjectileController projectile) { + gunController.onFireStart -= StartTracking; projectile.OnProjectileInit -= Track; projectile.OnColliderHit -= Target; projectile.OnRicochet -= Target; - garbagePool.Flush(); - garbagePool = null; - targetingReticlePool.Flush(); - targetingReticlePool = null; + OnDestroy(); } private void Track(ref ProjectileState state, GunStats stats) @@ -203,12 +197,9 @@ private void RpcTriggerImpactExplosion(Vector3 position) private void OnDestroy() { - if (!gunController) - return; - gunController.onFireStart -= StartTracking; - garbagePool.Flush(); + garbagePool?.Flush(); garbagePool = null; - targetingReticlePool.Flush(); + targetingReticlePool?.Flush(); targetingReticlePool = null; } } diff --git a/Assets/Scripts/Augment/AugmentImplementations/Solar/SolarBody.cs b/Assets/Scripts/Augment/AugmentImplementations/Solar/SolarBody.cs index f5bf30e46..2e791fafc 100644 --- a/Assets/Scripts/Augment/AugmentImplementations/Solar/SolarBody.cs +++ b/Assets/Scripts/Augment/AugmentImplementations/Solar/SolarBody.cs @@ -39,10 +39,14 @@ public class SolarBody : GunBody [SerializeField] private AudioGroup chargeDown; - public override void Start() + public void Start() { meshRenderer.materials[solarPanelMaterialIndex] = Instantiate(meshRenderer.materials[solarPanelMaterialIndex]); solarPanelMaterial = meshRenderer.materials[solarPanelMaterialIndex]; + } + + public override void Attach(GunController gunController) + { GameObject mainLight = GameObject.FindGameObjectsWithTag("MainLight")[0]; globalLightDirection = mainLight ? mainLight.transform : FindAnyObjectByType().transform; @@ -52,13 +56,20 @@ public override void Start() if (!gunController.Player) return; - playerHandRight.SetPlayer(gunController.Player); + playerHandRight.Subscribe(gunController.Player); playerHandRight.gameObject.SetActive(true); - playerHandLeft.SetPlayer(gunController.Player); + playerHandLeft.Subscribe(gunController.Player); playerHandLeft.gameObject.SetActive(true); audioSource = GetComponent(); } + public override void Detach(GunController gunController) + { + if (!gunController.Player) + return; + playerHandRight.Unsubscribe(gunController.Player); + playerHandLeft.Unsubscribe(gunController.Player); + } protected override void Reload(GunStats gunStats) { diff --git a/Assets/Scripts/Augment/AugmentImplementations/Telescope.cs b/Assets/Scripts/Augment/AugmentImplementations/Telescope.cs index 2b99afdd1..f6fe25476 100644 --- a/Assets/Scripts/Augment/AugmentImplementations/Telescope.cs +++ b/Assets/Scripts/Augment/AugmentImplementations/Telescope.cs @@ -10,19 +10,14 @@ public class Telescope : GunExtension [SerializeField] private float overrideZoomSpeed = 0.1f; - private GunController gunController; private List gunMeshes; private List gunSkinMeshes; private float originalZoomFov; private float originalZoomSpeed; - void Start() + public override void Attach(GunController gunController) { - gunController = transform.parent.GetComponent(); - if (!gunController) - return; - // Remove path altering modifiers so bullets always travel straight! gunController.GetComponentInChildren()? .GetModifiers() @@ -57,12 +52,21 @@ void Start() private void UnsubscribeZoom(PlayerManager killer, PlayerManager victim, DamageInfo info) { + Detach(gunController); + CancelZoom(); + } + + public override void Detach(GunController gunController) + { + if (!gunController.Player || !gunController.Player.HUDController) + return; + var playerMovement = gunController.Player.GetComponent(); playerMovement.ZoomFov = originalZoomFov; playerMovement.LookSpeedZoom = originalZoomSpeed; + gunController.Player.HUDController?.TweenScope(0, 0); gunController.Player.inputManager.onZoomPerformed -= OnZoom; gunController.Player.inputManager.onZoomCanceled -= OnZoomCanceled; - CancelZoom(); } private void OnZoom(InputAction.CallbackContext ctx) @@ -83,16 +87,4 @@ private void CancelZoom() gunSkinMeshes.ForEach((mesh) => mesh.enabled = true); gunController.Player.HUDController.TweenScope(0f, 0.2f); } - - private void OnDestroy() - { - if (!gunController || !gunController.Player || !gunController.Player.HUDController) - return; - var playerMovement = gunController.Player.GetComponent(); - playerMovement.ZoomFov = originalZoomFov; - playerMovement.LookSpeedZoom = originalZoomSpeed; - gunController.Player.HUDController?.TweenScope(0, 0); - gunController.Player.inputManager.onZoomPerformed -= OnZoom; - gunController.Player.inputManager.onZoomCanceled -= OnZoomCanceled; - } } diff --git a/Assets/Scripts/Augment/BulletModifiers/DecalModifier.cs b/Assets/Scripts/Augment/BulletModifiers/DecalModifier.cs index bd66c33fc..b04198035 100644 --- a/Assets/Scripts/Augment/BulletModifiers/DecalModifier.cs +++ b/Assets/Scripts/Augment/BulletModifiers/DecalModifier.cs @@ -48,8 +48,7 @@ public void Detach(ProjectileController projectile) { projectile.OnRicochet -= OnHit; } - decalPool.Flush(); - decalPool = null; + OnDestroy(); } private void OnHit(RaycastHit target, ref ProjectileState state) @@ -94,9 +93,7 @@ private Quaternion DetermineRotation(Collider target, ProjectileState state) private void OnDestroy() { - if (decalPool == null) - return; - decalPool.Flush(); + decalPool?.Flush(); decalPool = null; } } diff --git a/Assets/Scripts/Augment/BulletModifiers/InheritMomentumModifier.cs b/Assets/Scripts/Augment/BulletModifiers/InheritMomentumModifier.cs index 896bd6973..b121a89a3 100644 --- a/Assets/Scripts/Augment/BulletModifiers/InheritMomentumModifier.cs +++ b/Assets/Scripts/Augment/BulletModifiers/InheritMomentumModifier.cs @@ -47,6 +47,14 @@ public void Attach(ProjectileController projectile) projectile.OnProjectileInit += OnProjectileInit; } + public void Detach(ProjectileController projectile) + { + if (!projectile.GunController.Player) + return; + projectile.OnNetworkInit -= OnNetworkInit; + projectile.OnProjectileInit -= OnProjectileInit; + } + private void OnNetworkInit(ref ProjectileFireData data, GunStats _) { var speed = playerBody.velocity.magnitude; @@ -67,12 +75,4 @@ private void OnProjectileInit(ref ProjectileState state, GunStats stats) state.additionalProperties[ExplosionModifier.AreaDamagePropertyName] = damage * (1 - projectileToAreaDamageRatio); state.speed = Mathf.Max(1f, speed * speedMultiplier); } - - public void Detach(ProjectileController projectile) - { - if (!projectile.GunController.Player) - return; - projectile.OnNetworkInit -= OnNetworkInit; - projectile.OnProjectileInit -= OnProjectileInit; - } } diff --git a/Assets/Scripts/Augment/BulletModifiers/KnockbackOnShotModifier.cs b/Assets/Scripts/Augment/BulletModifiers/KnockbackOnShotModifier.cs index aa85d0b79..2111808cd 100644 --- a/Assets/Scripts/Augment/BulletModifiers/KnockbackOnShotModifier.cs +++ b/Assets/Scripts/Augment/BulletModifiers/KnockbackOnShotModifier.cs @@ -15,14 +15,9 @@ public class KnockbackOnShotModifier : MonoBehaviour, ProjectileModifier private (ProjectileState shot, List colliders) collidersHitWithShot = (null, new()); - private void Awake() - { - gunController = transform.parent.GetComponent(); - if (!gunController) - return; - } public void Attach(ProjectileController projectile) { + gunController = projectile.GunController; projectile.OnHitboxCollision += KnockAwayTargets; bulletAmount = projectile.stats.ProjectilesPerShot; calculatedPushPower = (pushPower / bulletAmount) * (1f + (float)Math.Log10(bulletAmount)); diff --git a/Assets/Scripts/Augment/BulletModifiers/RecoilModifier.cs b/Assets/Scripts/Augment/BulletModifiers/RecoilModifier.cs index da6a3a520..120a8f870 100644 --- a/Assets/Scripts/Augment/BulletModifiers/RecoilModifier.cs +++ b/Assets/Scripts/Augment/BulletModifiers/RecoilModifier.cs @@ -12,14 +12,9 @@ public class RecoilModifier : MonoBehaviour, ProjectileModifier private float calculatedPushPower; - private void Awake() - { - gunController = transform.parent.GetComponent(); - if (!gunController) - return; - } public void Attach(ProjectileController projectile) { + gunController = projectile.GunController; projectile.OnProjectileInit += KnockAwayOnShot; bulletAmount = projectile.stats.ProjectilesPerShot; calculatedPushPower = (pushPower / bulletAmount) * (1f + (float)Math.Log10(bulletAmount)); diff --git a/Assets/Scripts/Augment/BulletModifiers/StickyProjectileModifier.cs b/Assets/Scripts/Augment/BulletModifiers/StickyProjectileModifier.cs index e6f600196..242735362 100644 --- a/Assets/Scripts/Augment/BulletModifiers/StickyProjectileModifier.cs +++ b/Assets/Scripts/Augment/BulletModifiers/StickyProjectileModifier.cs @@ -55,8 +55,7 @@ public void Detach(ProjectileController projectile) { projectile.OnColliderHit -= StickToTarget; OnStuckToTarget = null; - stuckObjects.Flush(); - stuckObjects = null; + OnDestroy(); } public void StickToTarget(RaycastHit hit, ref ProjectileState state) @@ -64,8 +63,8 @@ public void StickToTarget(RaycastHit hit, ref ProjectileState state) if (!(affectedLayers == (affectedLayers | (1 << hit.collider.gameObject.layer)))) return; - var stuck = isDespawnedAfterTime ? - stuckObjects.GetAndReturnLater(stuckLifeTime) + var stuck = isDespawnedAfterTime ? + stuckObjects.GetAndReturnLater(stuckLifeTime) : stuckObjects.Get(); stuck.transform.position = hit.ClosestPoint(state.oldPosition); @@ -91,10 +90,7 @@ public StuckObject InstantiateManual(Vector3 position) private void OnDestroy() { - if (stuckObjects == null) - return; - - stuckObjects.Flush(); + stuckObjects?.Flush(); stuckObjects = null; } } diff --git a/Assets/Scripts/Augment/GunBarrel.cs b/Assets/Scripts/Augment/GunBarrel.cs index 7e09f9613..bcc5ac27d 100644 --- a/Assets/Scripts/Augment/GunBarrel.cs +++ b/Assets/Scripts/Augment/GunBarrel.cs @@ -7,7 +7,8 @@ public class GunBarrel : Augment { [SerializeField] private CrossHairModes crossHairMode; - // Where to attach extensions + + [Tooltip("Where to attach extensions")] public Transform[] attachmentPoints; public ProjectileController Projectile { get => GetComponent(); } @@ -37,6 +38,10 @@ private void Start() } } + public override void Attach(GunController gunController) { } + + public override void Detach(GunController gunController) { } + private void OnDestroy() { if (!gunController) @@ -44,6 +49,8 @@ private void OnDestroy() if (muzzleFlash) gunController.onFire -= PlayMuzzleFlash; + + Detach(gunController); } public void PlayMuzzleFlash(GunStats stats) diff --git a/Assets/Scripts/Augment/GunBody.cs b/Assets/Scripts/Augment/GunBody.cs index d0434f1fc..885631eeb 100644 --- a/Assets/Scripts/Augment/GunBody.cs +++ b/Assets/Scripts/Augment/GunBody.cs @@ -25,13 +25,9 @@ public class GunBody : NetworkBehaviour //TODO: Modifier refactor protected GunController gunController; - public virtual void Start() + protected virtual void Awake() { gunController = transform.parent.GetComponent(); - if (!gunController) - return; - // TODO: refactor this, which additionaly only exists to support placeholder weapons with no reload implementation - gunController.onFireEnd += Reload; } protected virtual void Reload(GunStats stats) @@ -40,9 +36,22 @@ protected virtual void Reload(GunStats stats) gunController.Reload(reloadEfficiencyPercentage); } - private void OnDestroy() + // TODO override this everywhere... + public virtual void Attach(GunController gunController) + { + // TODO: refactor this, which additionaly only exists to support placeholder weapons with no reload implementation + gunController.onFireEnd += Reload; + } + + public virtual void Detach(GunController gunController) { if (!gunController) return; gunController.onFireEnd -= Reload; } + + protected virtual void OnDestroy() + { + if (gunController) + Detach(gunController); + } } diff --git a/Assets/Scripts/Augment/GunExtension.cs b/Assets/Scripts/Augment/GunExtension.cs index 0ad6c6996..f9e47da6b 100644 --- a/Assets/Scripts/Augment/GunExtension.cs +++ b/Assets/Scripts/Augment/GunExtension.cs @@ -6,6 +6,23 @@ public class GunExtension : Augment [SerializeField] private GameObject model; + protected GunController gunController; + + protected void Awake() + { + gunController = transform.parent.GetComponent(); + } + + public override void Attach(GunController gunController) { } + + public override void Detach(GunController gunController) { } + + protected void OnDestroy() + { + if (gunController) + Detach(gunController); + } + /// /// Attaches the extension model(s) to each of the attachment points of the barrel. /// Required since a barrel can have multiple outputs (minigun). diff --git a/Assets/Scripts/Augment/GunFactory.cs b/Assets/Scripts/Augment/GunFactory.cs index 4ed830e19..a45ff4e5f 100644 --- a/Assets/Scripts/Augment/GunFactory.cs +++ b/Assets/Scripts/Augment/GunFactory.cs @@ -51,6 +51,7 @@ public static GameObject InstantiateGun(Item bodyPrefab, Item barrelPrefab, Item firstPersonGunController.RightHandTarget = displayGun.GunController.RightHandTarget; if (displayGun.GunController.HasRecoil) + // TODO pivot this to GunController... firstPersonGunController.onFire += displayGun.GunController.PlayRecoil; if (displayGun.GunController.projectile is BulletController) @@ -65,6 +66,7 @@ public static GameObject InstantiateGun(Item bodyPrefab, Item barrelPrefab, Item return gun; } + // TODO does this one really do anything??? public static void UnsubscribeAnimators(GameObject gun) { var firstPersonGunController = gun.GetComponent().GunController; diff --git a/Assets/Scripts/Augment/PlayerHand.cs b/Assets/Scripts/Augment/PlayerHand.cs index 342a0df32..1d30e01d8 100644 --- a/Assets/Scripts/Augment/PlayerHand.cs +++ b/Assets/Scripts/Augment/PlayerHand.cs @@ -1,7 +1,6 @@ -using System; using UnityEngine; -public class PlayerHand : MonoBehaviour +public class PlayerHand : MonoBehaviour, PlayerSubscriber { [SerializeField] private SkinnedMeshRenderer handMaterial; @@ -10,9 +9,8 @@ public class PlayerHand : MonoBehaviour [SerializeField] private Transform holdingPoint; public Transform HoldingPoint => holdingPoint; - private Action unsubscribePlayer; - public void SetPlayer(PlayerManager player) + public void Subscribe(PlayerManager player) { handMaterial.material.color = player.identity.color; if (player.inputManager) @@ -28,14 +26,13 @@ public void SetPlayer(PlayerManager player) if (MatchController.Singleton) MatchController.Singleton.onRoundEnd += DisableHand; player.onDeath += DisableHand; - unsubscribePlayer = () => player.onDeath -= DisableHand; } - private void OnDestroy() + public void Unsubscribe(PlayerManager player) { if (MatchController.Singleton) MatchController.Singleton.onRoundEnd -= DisableHand; - unsubscribePlayer?.Invoke(); + player.onDeath -= DisableHand; } private void DisableHand(PlayerManager killer, PlayerManager victim, DamageInfo info) diff --git a/Assets/Scripts/Augment/ProjectileModifier.cs b/Assets/Scripts/Augment/ProjectileModifier.cs index 88c040ae8..4d7f9f5f2 100644 --- a/Assets/Scripts/Augment/ProjectileModifier.cs +++ b/Assets/Scripts/Augment/ProjectileModifier.cs @@ -8,6 +8,7 @@ public enum Priority EXTENSION, ARBITRARY } + /// /// An interface that can be implemented in order to give additional functional property to any projectile created by any set of parts. /// Why? Because putting a copy of every needed bullet script on every single bullet that is created is very inefficient. @@ -16,12 +17,12 @@ public enum Priority /// /// Note: Behaviour tied to updating the projectile every frame (Update), should be done with ProjectileController delegates instead! /// -public interface ProjectileModifier +public interface ProjectileModifier { public abstract void Attach(ProjectileController projectile); public abstract void Detach(ProjectileController projectile); - public Priority GetPriority() + public Priority GetPriority() { return Priority.ARBITRARY; } diff --git a/Assets/Scripts/Extensions/PortalExtension/PortalExtensionController.cs b/Assets/Scripts/Extensions/PortalExtension/PortalExtensionController.cs index b0b926ac5..942195a78 100644 --- a/Assets/Scripts/Extensions/PortalExtension/PortalExtensionController.cs +++ b/Assets/Scripts/Extensions/PortalExtension/PortalExtensionController.cs @@ -12,41 +12,35 @@ public class PortalExtensionController : GunExtension private Transform portalMover; - private GunController gunController; - private Transform playerView; private InputManager inputManager; [SerializeField] private LayerMask validPortalSurfaceColliders, validAimColliders; - private void Start() + public override void Attach(GunController gunController) { - if (!gunController) - gunController = GetComponentInParent(); + gunController.AimCorrectionEnabled = false; + inputManager = gunController.Player ? gunController.Player.inputManager : null; + if (inputManager) + playerView = inputManager.transform; + } - if (gunController != null) - { - gunController.AimCorrectionEnabled = false; - inputManager = GetComponentInParent().inputManager; - if (inputManager) - playerView = inputManager.transform; - } + public override void Detach(GunController gunController) + { + gunController.AimCorrectionEnabled = true; } - private void OnDestroy() + private new void OnDestroy() { - if (gunController) - gunController.AimCorrectionEnabled = true; + base.OnDestroy(); if (portalMover) Destroy(portalMover.gameObject); } - private void MovePortal() { - RaycastHit hit; - if (Physics.Raycast(playerView.position, playerView.forward, out hit, 200, this.validPortalSurfaceColliders)) + if (Physics.Raycast(playerView.position, playerView.forward, out RaycastHit hit, 200, this.validPortalSurfaceColliders)) { portalMover.rotation = Quaternion.LookRotation(-hit.normal, Vector3.up); portalMover.position = hit.point + 0.9f * hit.normal; diff --git a/Assets/Scripts/Gamestate/PlayerManager.cs b/Assets/Scripts/Gamestate/PlayerManager.cs index f30b53ffd..81fe74b7f 100644 --- a/Assets/Scripts/Gamestate/PlayerManager.cs +++ b/Assets/Scripts/Gamestate/PlayerManager.cs @@ -1,7 +1,6 @@ using Mirror; using System.Collections; using System.Linq; -using Unity.VisualScripting.Antlr3.Runtime.Misc; using UnityEngine; using UnityEngine.InputSystem; using UnityEngine.Rendering.Universal; @@ -263,6 +262,8 @@ public void SetPlayerInput(InputManager playerInput) var canvas = hudController.GetComponent(); canvas.worldCamera = inputManager.GetComponentInChildren(); canvas.planeDistance = 0.21f; + // TODO pivot inside HUDController (for respawning) + // and remember -= identity.onChipChange += hudController.OnChipChange; // Disable arena camera so we don't render the entire scene twice @@ -326,10 +327,7 @@ void OnDestroy() } if (gunController) { - gunController.onFireStart -= UpdateAimTarget; - gunController.onFire -= UpdateAimTarget; - gunController.onFireEnd -= UpdateHudFire; - gunController.onReload -= UpdateHudReload; + UnsubscribeGun(); //Remove the gun Destroy(gunController.gameObject); } @@ -515,13 +513,7 @@ public virtual void SetGun(Transform offset) var hadGunBefore = gunController != null; if (hadGunBefore && inputManager) { - gunController.onFireStart -= UpdateAimTarget; - gunController.onFire -= UpdateAimTarget; - gunController.onFire -= ScreenShake; - gunController.onFireEnd -= UpdateHudFire; - gunController.onReload -= UpdateHudReload; - gunController.projectile.OnHitboxCollision -= hudController.HitAnimation; - GunFactory.UnsubscribeAnimators(gunController.gameObject); + UnsubscribeGun(); } overrideAimTarget = false; var gun = GunFactory.InstantiateGun(identity.Body, identity.Barrel, identity.Extension, this, offset); @@ -538,7 +530,7 @@ public virtual void SetGun(Transform offset) gunController.onFireEnd += UpdateHudFire; gunController.onReload += UpdateHudReload; UpdateHudCrosshair(gunController.stats); - gunController.projectile.OnHitboxCollision += hudController.HitAnimation; + hudController.Attach(gunController); } playerIK.LeftHandIKTarget = gunController.LeftHandTarget; if (gunController.RightHandTarget) @@ -549,6 +541,17 @@ public virtual void SetGun(Transform offset) GetComponent().InitializeNetworkBehaviours(); } + private void UnsubscribeGun() + { + gunController.onFireStart -= UpdateAimTarget; + gunController.onFire -= UpdateAimTarget; + gunController.onFire -= ScreenShake; + gunController.onFireEnd -= UpdateHudFire; + gunController.onReload -= UpdateHudReload; + hudController.Detach(gunController); + GunFactory.UnsubscribeAnimators(gunController.gameObject); + } + public void SetGunNetwork(Transform offset) { overrideAimTarget = false; diff --git a/Assets/Scripts/Gamestate/PlayerSubscriber.cs b/Assets/Scripts/Gamestate/PlayerSubscriber.cs new file mode 100644 index 000000000..3c3ac3ca2 --- /dev/null +++ b/Assets/Scripts/Gamestate/PlayerSubscriber.cs @@ -0,0 +1,5 @@ +public interface PlayerSubscriber +{ + void Subscribe(PlayerManager player); + void Unsubscribe(PlayerManager player); +} \ No newline at end of file diff --git a/Assets/Scripts/UI/PlayerHUDController.cs b/Assets/Scripts/UI/PlayerHUDController.cs index f7b0d2d24..852941d45 100644 --- a/Assets/Scripts/UI/PlayerHUDController.cs +++ b/Assets/Scripts/UI/PlayerHUDController.cs @@ -342,7 +342,17 @@ public void MoveCrosshair(float x, float y) crosshair.rectTransform.anchoredPosition = (new Vector2(halfWidth * x, halfHeight * y)); } - public void HitAnimation(HitboxController other, ref ProjectileState state) + public void Attach(GunController gunController) + { + gunController.projectile.OnHitboxCollision += HitAnimation; + } + + public void Detach(GunController gunController) + { + gunController.projectile.OnHitboxCollision -= HitAnimation; + } + + private void HitAnimation(HitboxController other, ref ProjectileState state) { if (LeanTween.isTweening(hitTween)) { diff --git a/Assets/Scripts/Utils/ObjectPool.cs b/Assets/Scripts/Utils/ObjectPool.cs index e2ee4e5ec..dd8daeed5 100644 --- a/Assets/Scripts/Utils/ObjectPool.cs +++ b/Assets/Scripts/Utils/ObjectPool.cs @@ -1,6 +1,5 @@ using System.Collections; using System.Collections.Generic; -using Unity.VisualScripting; using UnityEngine; public class ObjectPool where T : MonoBehaviour @@ -138,7 +137,7 @@ public void Return(T instance) if (!instance) return; instance.gameObject.SetActive(false); - instance.transform.SetParent(parent.transform,true); + instance.transform.SetParent(parent.transform, true); instance.transform.position = parent.transform.position; instance.transform.rotation = parent.transform.rotation; } @@ -148,7 +147,7 @@ public void Return(T instance) /// public void ReturnAll() { - foreach(var instance in pool) + foreach (var instance in pool) Return(instance); } } diff --git a/Assets/SodiePopper.cs b/Assets/SodiePopper.cs index e1238d456..5c02d27d0 100644 --- a/Assets/SodiePopper.cs +++ b/Assets/SodiePopper.cs @@ -1,5 +1,3 @@ -using System.Collections; -using System.Collections.Generic; using UnityEngine; public class SodiePopper : GunBody @@ -54,24 +52,29 @@ public class SodiePopper : GunBody [SerializeField] private AudioGroup slosh; - public override void Start() + private void Start() { - gunController = transform.parent?.GetComponent(); - lastPos = lastLastPos = meassurementPoint.position; + } - if (!gunController) - return; + public override void Attach(GunController gunController) + { gunController.HasRecoil = false; if (!gunController.Player) return; audioSource = GetComponent(); playerBody = gunController.Player.GetComponent().Body; - playerHandRight.SetPlayer(gunController.Player); + playerHandRight.Subscribe(gunController.Player); playerHandRight.gameObject.SetActive(true); } + public override void Detach(GunController gunController) + { + if (gunController.Player) + playerHandRight.Unsubscribe(gunController.Player); + } + private void Update() { if (gunController != null) From 6031b08a256578c3109ffdd630656201c811b3d0 Mon Sep 17 00:00:00 2001 From: Tore Bergebakken Date: Mon, 21 Apr 2025 01:03:26 +0200 Subject: [PATCH 2/3] dear god --- .../Hat/MeshProjectileController.cs | 3 ++ .../AugmentImplementations/LawnMower.cs | 1 + .../Augment/AugmentImplementations/Pan.cs | 12 ++++- .../AugmentImplementations/RopeBody.cs | 5 +- .../AugmentImplementations/Telescope.cs | 3 ++ .../AugmentImplementations/TetherPlug.cs | 3 -- Assets/Scripts/Augment/BulletController.cs | 4 ++ Assets/Scripts/Augment/GunBody.cs | 1 - Assets/Scripts/Augment/GunController.cs | 30 ++++++++++- Assets/Scripts/Augment/GunFactory.cs | 53 ++++++++----------- Assets/Scripts/Augment/GunStats.cs | 1 + .../Scripts/Augment/ProjectileController.cs | 3 ++ Assets/Scripts/Gamestate/PlayerManager.cs | 36 ++----------- .../Gamestate/PlayerSubscriber.cs.meta | 11 ++++ Assets/Scripts/UI/PlayerHUDController.cs | 29 ++++++---- Assets/Scripts/Utils/ObjectPool.cs | 3 +- 16 files changed, 117 insertions(+), 81 deletions(-) create mode 100644 Assets/Scripts/Gamestate/PlayerSubscriber.cs.meta diff --git a/Assets/Scripts/Augment/AugmentImplementations/Hat/MeshProjectileController.cs b/Assets/Scripts/Augment/AugmentImplementations/Hat/MeshProjectileController.cs index 2a144ec4e..1741b241a 100644 --- a/Assets/Scripts/Augment/AugmentImplementations/Hat/MeshProjectileController.cs +++ b/Assets/Scripts/Augment/AugmentImplementations/Hat/MeshProjectileController.cs @@ -102,6 +102,9 @@ protected override void OnDestroy() base.OnDestroy(); positionActiveBuffer?.Dispose(); rotationBuffer?.Dispose(); + UpdateProjectileMovement -= ProjectileMotions.MoveWithGravity; + if (animator) + animator.OnShotFiredAnimation -= FireProjectile; } protected override void OnInitialize(GunStats gunstats) diff --git a/Assets/Scripts/Augment/AugmentImplementations/LawnMower.cs b/Assets/Scripts/Augment/AugmentImplementations/LawnMower.cs index 2c0d23591..78ff5ea05 100644 --- a/Assets/Scripts/Augment/AugmentImplementations/LawnMower.cs +++ b/Assets/Scripts/Augment/AugmentImplementations/LawnMower.cs @@ -75,6 +75,7 @@ public override void Attach(GunController gunController) handString.gameObject.SetActive(true); if (gunController.Player.GunOrigin.TryGetComponent(out GunController gunControllerDisplay)) + // TODO nullref at this point gunControllerDisplay.GetComponentInChildren().LineHoldingPoint = gunController.Player.PlayerIK.LeftHandIKTransform; } diff --git a/Assets/Scripts/Augment/AugmentImplementations/Pan.cs b/Assets/Scripts/Augment/AugmentImplementations/Pan.cs index 91aa4859f..1ccef804f 100644 --- a/Assets/Scripts/Augment/AugmentImplementations/Pan.cs +++ b/Assets/Scripts/Augment/AugmentImplementations/Pan.cs @@ -56,16 +56,21 @@ public override void Attach(GunController gunController) public override void Detach(GunController gunController) { + if (playerMovement) + playerMovement.OnMove -= TryPanSkateBoost; + if (!gunController.Player) return; if (gunController.Player.inputManager) gunController.Player.inputManager.onSelect -= TryTrickJump; - if (playerMovement) - playerMovement.OnMove -= TryPanSkateBoost; } + // TODO for some reason this one might not be unsubbed properly??? private void TryTrickJump(InputAction.CallbackContext ctx) { + // Avoid issue here... + if (!gunController) + return; bool isCorrectMovement = playerMovement && playerMovement.StateIsAir && playerMovement.IsCrouching; var isNotFlying = Mathf.Abs(playerMovement.Body.velocity.y) < 0.01f; if (isCorrectMovement && isNotFlying && playerMovement.Body.velocity.magnitude > 1f) @@ -76,6 +81,9 @@ private void TryTrickJump(InputAction.CallbackContext ctx) private void TryPanSkateBoost(Rigidbody body) { + // Avoid issue here... + if (!gunController) + return; bool isSkating = playerMovement.StateIsAir && playerMovement.IsCrouching && Mathf.Abs(body.velocity.y) < 0.01f; bool isMoving = gunController.Player.inputManager.moveInput.magnitude > 0.5f; if (!isMoving || !isSkating) diff --git a/Assets/Scripts/Augment/AugmentImplementations/RopeBody.cs b/Assets/Scripts/Augment/AugmentImplementations/RopeBody.cs index d123c1f81..ef59894f6 100644 --- a/Assets/Scripts/Augment/AugmentImplementations/RopeBody.cs +++ b/Assets/Scripts/Augment/AugmentImplementations/RopeBody.cs @@ -1,6 +1,5 @@ using System.Linq; using Mirror; -using Org.BouncyCastle.Asn1.Misc; using UnityEngine; public class RopeBody : GunBody @@ -56,10 +55,12 @@ private void Start() } } + // TODO somehow you're able to shoot once before requiring the plug??? public override void Attach(GunController gunController) { if (!gunController.Player) return; + base.Attach(gunController); rope.Line.gameObject.layer = 0; rope.Target = ropeTarget; plugAnchor = Instantiate(plugAnchorPrefab); @@ -81,6 +82,7 @@ public override void Attach(GunController gunController) public override void Detach(GunController gunController) { + base.Detach(gunController); if (!plugAnchor) return; plugAnchor.Health.onDeath -= RemoveRope; @@ -95,6 +97,7 @@ public override void Detach(GunController gunController) protected override void OnDestroy() { base.OnDestroy(); + // TODO this destruction does not work? Destroy(plugAnchor); } diff --git a/Assets/Scripts/Augment/AugmentImplementations/Telescope.cs b/Assets/Scripts/Augment/AugmentImplementations/Telescope.cs index f6fe25476..abef9c984 100644 --- a/Assets/Scripts/Augment/AugmentImplementations/Telescope.cs +++ b/Assets/Scripts/Augment/AugmentImplementations/Telescope.cs @@ -32,6 +32,9 @@ public override void Attach(GunController gunController) if (gunController.GetComponentInChildren()) return; + // TODO somehow the FOV manipulation goes haywire when picking telescope multiple times + // - that is, attaching and detaching multiple times seems to increase FOV every time... + // makes me think we should not keep track of original FOV here, but rather inside playermovement var playerMovement = gunController.Player.GetComponent(); originalZoomFov = playerMovement.ZoomFov; originalZoomSpeed = playerMovement.LookSpeedZoom; diff --git a/Assets/Scripts/Augment/AugmentImplementations/TetherPlug.cs b/Assets/Scripts/Augment/AugmentImplementations/TetherPlug.cs index 227ef2dba..e9f9919f6 100644 --- a/Assets/Scripts/Augment/AugmentImplementations/TetherPlug.cs +++ b/Assets/Scripts/Augment/AugmentImplementations/TetherPlug.cs @@ -1,7 +1,4 @@ -using System.Collections; -using System.Collections.Generic; using UnityEngine; -using UnityEngine.VFX; public class TetherPlug : MonoBehaviour { diff --git a/Assets/Scripts/Augment/BulletController.cs b/Assets/Scripts/Augment/BulletController.cs index 339410a14..15154d238 100644 --- a/Assets/Scripts/Augment/BulletController.cs +++ b/Assets/Scripts/Augment/BulletController.cs @@ -45,6 +45,7 @@ protected override void Awake() base.Awake(); if (!gunController || !gunController.Player) return; + // TODO these must be unsubbed? UpdateProjectileMovement += ProjectileMotions.MoveWithGravity; animator.OnShotFiredAnimation += FireProjectile; } @@ -68,6 +69,9 @@ protected override void OnDestroy() { base.OnDestroy(); trailPositionBuffer?.Dispose(); + UpdateProjectileMovement -= ProjectileMotions.MoveWithGravity; + if (animator) + animator.OnShotFiredAnimation -= FireProjectile; } diff --git a/Assets/Scripts/Augment/GunBody.cs b/Assets/Scripts/Augment/GunBody.cs index 885631eeb..a5f0130ca 100644 --- a/Assets/Scripts/Augment/GunBody.cs +++ b/Assets/Scripts/Augment/GunBody.cs @@ -45,7 +45,6 @@ public virtual void Attach(GunController gunController) public virtual void Detach(GunController gunController) { - if (!gunController) return; gunController.onFireEnd -= Reload; } diff --git a/Assets/Scripts/Augment/GunController.cs b/Assets/Scripts/Augment/GunController.cs index 2c7598e3b..5eb863fbb 100644 --- a/Assets/Scripts/Augment/GunController.cs +++ b/Assets/Scripts/Augment/GunController.cs @@ -106,11 +106,32 @@ public void Initialize() private void OnDestroy() { - UnsubscribeDelegates(); + Detach(); } - public void UnsubscribeDelegates() + // TODO perhaps avoid too many duplacte detach calls? + public void Detach() { + // TODO remember these after init? + var body = GetComponentInChildren(); + var barrel = GetComponentInChildren(); + var extension = GetComponentInChildren(); + + if (barrel == null) + Debug.LogWarning("Gun already detached!"); + + // TODO nullref here... + var modifiers = barrel.GetModifiers(); + if (extension) + modifiers.AddRange(extension.GetModifiers()); + modifiers.ForEach(m => m.Detach(projectile)); + + body.Detach(this); + barrel.Detach(this); + if (extension) + extension.Detach(this); + + // TODO the null-ing is hopefully not necessary? onInitializeGun = null; onFire = null; onFireEnd = null; @@ -145,6 +166,11 @@ public void UnsubscribeDelegates() Player.inputManager.onZoomPerformed -= OnZoom; Player.inputManager.onZoomCanceled -= OnZoomCanceled; + // Unset player field so we don't reapply resets multiple times + // (happened with the telescope body) + // TODO this doesn't fix the issue entirely of course... + Player = null; + if (MatchController.Singleton) MatchController.Singleton.onRoundEnd -= CancelZoom; } diff --git a/Assets/Scripts/Augment/GunFactory.cs b/Assets/Scripts/Augment/GunFactory.cs index a45ff4e5f..c82814ae9 100644 --- a/Assets/Scripts/Augment/GunFactory.cs +++ b/Assets/Scripts/Augment/GunFactory.cs @@ -10,6 +10,13 @@ public class GunFactory : MonoBehaviour { public static GameObject InstantiateGun(Item bodyPrefab, Item barrelPrefab, Item extensionPrefab, PlayerManager owner, Transform parent) { + // Create display gun first (some components assume its existence) + GunFactory displayGun = owner.GunOrigin.GetComponent(); + displayGun.Body = bodyPrefab; + displayGun.Barrel = barrelPrefab; + displayGun.Extension = extensionPrefab; + displayGun.InitializeGun(); + GameObject gun = Instantiate(new GameObject(), parent); GunFactory controller = gun.AddComponent(); controller.Body = bodyPrefab; @@ -22,12 +29,6 @@ public static GameObject InstantiateGun(Item bodyPrefab, Item barrelPrefab, Item var playerIndex = owner.inputManager && owner.inputManager.playerInput ? owner.inputManager.playerInput.playerIndex : 3; var cullingLayer = LayerMask.NameToLayer("Gun " + playerIndex); - GunFactory displayGun = owner.GunOrigin.GetComponent(); - displayGun.Body = bodyPrefab; - displayGun.Barrel = barrelPrefab; - displayGun.Extension = extensionPrefab; - displayGun.InitializeGun(); - var cullingLayerDisplay = LayerMask.NameToLayer("Player " + playerIndex); var firstPersonGunController = gun.GetComponent().GunController; @@ -66,14 +67,6 @@ public static GameObject InstantiateGun(Item bodyPrefab, Item barrelPrefab, Item return gun; } - // TODO does this one really do anything??? - public static void UnsubscribeAnimators(GameObject gun) - { - var firstPersonGunController = gun.GetComponent().GunController; - firstPersonGunController.onFireStart = null; - firstPersonGunController.onReload = null; - } - public static GameObject InstantiateGunAI(Item bodyPrefab, Item barrelPrefab, Item extensionPrefab, PlayerManager owner, Transform parent) { GunFactory displayGun = owner.GunOrigin.gameObject.AddComponent(); @@ -244,14 +237,16 @@ public void InitializeGun(PlayerManager owner = null) modifiers.AddRange(gunBarrel.GetModifiers()); gunBarrel.BuildStats(gunController.stats); + GunExtension gunExtension = null; + if (Extension != null) { // Instantiate extension itself *once* #if UNITY_EDITOR - GunExtension gunExtension = ((GameObject)PrefabUtility.InstantiatePrefab(Extension.augment, transform)) + gunExtension = ((GameObject)PrefabUtility.InstantiatePrefab(Extension.augment, transform)) .GetComponent(); #else - GunExtension gunExtension = Instantiate(Extension.augment, transform) + gunExtension = Instantiate(Extension.augment, transform) .GetComponent(); #endif gunExtension.transform.position = gunBarrel.attachmentPoints[0].position; @@ -265,6 +260,7 @@ public void InitializeGun(PlayerManager owner = null) modifiers.AddRange(gunExtension.GetModifiers()); gunExtension.BuildStats(gunController.stats); + gunExtension.Attach(gunController); } else { @@ -276,27 +272,24 @@ public void InitializeGun(PlayerManager owner = null) gunController.projectile.stats = gunController.stats; + gunBody.Attach(gunController); + gunBarrel.Attach(gunController); + if (gunExtension) + gunExtension.Attach(gunController); + modifiers.OrderByDescending(modifier => (int)modifier.GetPriority()).ToList(); modifiers.ForEach(modifier => modifier.Attach(gunController.projectile)); gunController.onInitializeGun?.Invoke(gunController.stats); // Moved it below the stat changes so the stats actually, yknow, affect the firerate. // Will be removed anyways when the firemode system is updated to accomodate a wider variety of guns - switch (gunController.stats.fireMode) + gunController.fireRateController = gunController.stats.fireMode switch { - case GunStats.FireModes.SemiAuto: - gunController.fireRateController = new SemiAutoFirerateController(gunController.stats.Firerate); - break; - case GunStats.FireModes.Burst: - gunController.fireRateController = new BurstFirerateController(gunController.stats.Firerate, gunController.stats.burstNum); - break; - case GunStats.FireModes.FullAuto: - gunController.fireRateController = new FullAutoFirerateController(gunController.stats.Firerate); - break; - default: - gunController.fireRateController = new FullAutoFirerateController(gunController.stats.Firerate); - break; - } + GunStats.FireModes.SemiAuto => new SemiAutoFirerateController(gunController.stats.Firerate), + GunStats.FireModes.Burst => new BurstFirerateController(gunController.stats.Firerate, gunController.stats.burstNum), + GunStats.FireModes.FullAuto => new FullAutoFirerateController(gunController.stats.Firerate), + _ => new FullAutoFirerateController(gunController.stats.Firerate), + }; // Ensure ammo == magazineSize after all modifiers are applied gunController.Reload(1); } diff --git a/Assets/Scripts/Augment/GunStats.cs b/Assets/Scripts/Augment/GunStats.cs index 18e047de7..0eea17667 100644 --- a/Assets/Scripts/Augment/GunStats.cs +++ b/Assets/Scripts/Augment/GunStats.cs @@ -52,6 +52,7 @@ public enum FireModes /// [HideInInspector] public int Ammo = 0; + public float AmmoPercent => (Ammo < 1 ? 0 : Ammo) / (float)MagazineSize; [SerializeField] [Tooltip("Damage of each projectile")] diff --git a/Assets/Scripts/Augment/ProjectileController.cs b/Assets/Scripts/Augment/ProjectileController.cs index 6fde67041..a3959a4ec 100644 --- a/Assets/Scripts/Augment/ProjectileController.cs +++ b/Assets/Scripts/Augment/ProjectileController.cs @@ -215,7 +215,10 @@ protected virtual void OnDestroy() gunController.onReload -= OnReload; } + // TODO go through all projectile controllers... + + // TODO add a detach as well... or does ondestroy work fine here? 🤔 protected abstract void OnInitialize(GunStats stats); protected abstract void OnReload(GunStats stats); diff --git a/Assets/Scripts/Gamestate/PlayerManager.cs b/Assets/Scripts/Gamestate/PlayerManager.cs index 81fe74b7f..8b0b09c69 100644 --- a/Assets/Scripts/Gamestate/PlayerManager.cs +++ b/Assets/Scripts/Gamestate/PlayerManager.cs @@ -327,9 +327,7 @@ void OnDestroy() } if (gunController) { - UnsubscribeGun(); - //Remove the gun - Destroy(gunController.gameObject); + RemoveGun(); } if (TryGetComponent(out PlayerMovement playerMovement)) { @@ -409,26 +407,6 @@ private void PlayLeapAudio(Rigidbody body) leapSounds.Play(audioSource); } - private void UpdateHudFire(GunStats stats) - { - // stats variables must be dereferenced - float ammo = stats.Ammo < 1 ? 0 : stats.Ammo; - float magazine = stats.MagazineSize; - hudController.UpdateOnFire(ammo / magazine); - } - - private void UpdateHudReload(GunStats stats) - { - float ammo = stats.Ammo; - float magazine = stats.MagazineSize; - hudController.UpdateOnReload(ammo / magazine); - } - - private void UpdateHudCrosshair(GunStats stats) - { - HUDController.UpdateOnInitialize(stats); - } - private void TryPlaceBid(InputAction.CallbackContext ctx) { if (!selectedBiddingPlatform) return; @@ -527,9 +505,6 @@ public virtual void SetGun(Transform offset) gunController.onFireStart += UpdateAimTarget; gunController.onFire += UpdateAimTarget; gunController.onFire += ScreenShake; - gunController.onFireEnd += UpdateHudFire; - gunController.onReload += UpdateHudReload; - UpdateHudCrosshair(gunController.stats); hudController.Attach(gunController); } playerIK.LeftHandIKTarget = gunController.LeftHandTarget; @@ -546,10 +521,9 @@ private void UnsubscribeGun() gunController.onFireStart -= UpdateAimTarget; gunController.onFire -= UpdateAimTarget; gunController.onFire -= ScreenShake; - gunController.onFireEnd -= UpdateHudFire; - gunController.onReload -= UpdateHudReload; hudController.Detach(gunController); - GunFactory.UnsubscribeAnimators(gunController.gameObject); + gunController.Detach(); + GunOrigin.GetComponent().Detach(); } public void SetGunNetwork(Transform offset) @@ -569,17 +543,17 @@ public void SetGunNetwork(Transform offset) public void RemoveGun() { - gunController.UnsubscribeDelegates(); + UnsubscribeGun(); for (int i = gunController.transform.childCount - 1; i >= 0; i--) { Destroy(gunController.transform.GetChild(i).gameObject); } Destroy(gunController.gameObject); - GunOrigin.GetComponent().UnsubscribeDelegates(); for (int i = GunOrigin.transform.childCount - 1; i >= 0; i--) { Destroy(GunOrigin.transform.GetChild(i).gameObject); } + // TODO ok and why don't we destroy the guncontroller for the display gun } private void SetLayerOnSubtree(GameObject node, int layer) diff --git a/Assets/Scripts/Gamestate/PlayerSubscriber.cs.meta b/Assets/Scripts/Gamestate/PlayerSubscriber.cs.meta new file mode 100644 index 000000000..5c4fdea42 --- /dev/null +++ b/Assets/Scripts/Gamestate/PlayerSubscriber.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b8fc29f19163bf446af0038304048a81 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/UI/PlayerHUDController.cs b/Assets/Scripts/UI/PlayerHUDController.cs index 852941d45..ff3630725 100644 --- a/Assets/Scripts/UI/PlayerHUDController.cs +++ b/Assets/Scripts/UI/PlayerHUDController.cs @@ -2,7 +2,6 @@ using UnityEngine.UI; using System.Linq; using TMPro; -using UnityEngine.Serialization; using static GunStats; using System; @@ -122,13 +121,11 @@ private void Awake() { crosshairMaterial = Instantiate(crosshair.material); crosshair.material = crosshairMaterial; - } - void Start() - { speedLines.material = Instantiate(speedLines.material); speedLinesMaterial = speedLines.material; speedLines.gameObject.SetActive(true); + var image = GetComponent(); // Prevent material properties from being handled globally damageBorder = Instantiate(image.material); @@ -138,7 +135,10 @@ void Start() ammoCapacityMaterial = Instantiate(ammoBar.material); ammoBar.material = ammoCapacityMaterial; ammoCapacityMaterial.SetFloat("_Arc2", 0); + } + private void Start() + { originalChipY = chipBox.anchoredPosition.y; if (!MatchController.Singleton || PlayerInputManagerController.Singleton.LocalPlayerInputs.Count() == 1) { @@ -237,7 +237,7 @@ private void SetChipBoxPosition(float height) chipBox.anchoredPosition = new Vector2(originalChipX, originalChipY - height * 2 * originalChipY); } - public void UpdateOnFire(float ammoPercent) + public void UpdateOnFire(GunStats stats) { if (LeanTween.isTweening(ammoTween)) { @@ -245,15 +245,15 @@ public void UpdateOnFire(float ammoPercent) ammoBar.gameObject.transform.eulerAngles = new Vector3(ammoBar.gameObject.transform.eulerAngles.x, ammoBar.gameObject.transform.eulerAngles.y, 0); } - ammoCapacityMaterial.SetFloat("_Arc2", (1 - ammoPercent) * availableDegrees); + UpdateAmmoBar(stats); ammoTween = ammoHud.gameObject.LeanRotateAroundLocal(Vector3.forward, ammoSpinDegrees, 0.5f).setEaseSpring() .setOnStart( () => ammoBar.gameObject.transform.Rotate(new Vector3(0, 0, -ammoSpinDegrees))).id; } - public void UpdateOnReload(float ammoPercent) + private void UpdateAmmoBar(GunStats stats) { - ammoCapacityMaterial.SetFloat("_Arc2", (1 - ammoPercent) * availableDegrees); + ammoCapacityMaterial.SetFloat("_Arc2", (1 - stats.AmmoPercent) * availableDegrees); } private void UpdateHealthBar(float currentHealth, float maxHealth) @@ -298,7 +298,7 @@ public void UpdateDamageBorder(float intensity) { // Start of curve, reach the top quickly // Always start at 0 so we get proper damage indication each time we get hit - intensity = intensity * (1 / damageBorderTop); + intensity *= 1 / damageBorderTop; } else { @@ -345,11 +345,20 @@ public void MoveCrosshair(float x, float y) public void Attach(GunController gunController) { gunController.projectile.OnHitboxCollision += HitAnimation; + gunController.onFireEnd += UpdateOnFire; + gunController.onReload += UpdateAmmoBar; + + // Ensure ammo correctness at attach time + UpdateAmmoBar(gunController.stats); + + InitializeCrosshair(gunController.stats); } public void Detach(GunController gunController) { gunController.projectile.OnHitboxCollision -= HitAnimation; + gunController.onFireEnd -= UpdateOnFire; + gunController.onReload -= UpdateAmmoBar; } private void HitAnimation(HitboxController other, ref ProjectileState state) @@ -410,7 +419,7 @@ public void CrossHairDetonationAnimation() .setOnComplete(() => SetCrosshairRadius(initialCrosshairRadius)).id; } - public void UpdateOnInitialize(GunStats stats) + public void InitializeCrosshair(GunStats stats) { initialCrosshairRadius = stats.CrosshairRadius.Value() == 0f ? 0f : 1f / stats.CrosshairRadius.Value(); crosshairMaterial.SetFloat("_Radius", initialCrosshairRadius); diff --git a/Assets/Scripts/Utils/ObjectPool.cs b/Assets/Scripts/Utils/ObjectPool.cs index dd8daeed5..1c83eb908 100644 --- a/Assets/Scripts/Utils/ObjectPool.cs +++ b/Assets/Scripts/Utils/ObjectPool.cs @@ -26,7 +26,8 @@ private ObjectPool(int capacity) /// public void Flush() { - pool.ForEach(gameObject => GameObject.Destroy(gameObject)); + pool?.ForEach(gameObject => GameObject.Destroy(gameObject)); + // TODO setting it to null is kinda troublesome, had to add a ?. above... pool = null; if (parent != null) GameObject.Destroy(parent.gameObject); From 3c66c67cbf9aa510ad587f7dce3c9d4ed5543435 Mon Sep 17 00:00:00 2001 From: Tore Bergebakken Date: Mon, 21 Apr 2025 22:56:00 +0200 Subject: [PATCH 3/3] dear god what have I brought upon us --- Assets/PinAnimator.cs | 14 +++++++++++- .../BoomBardierAnimator.cs | 22 +++++++++++++------ 2 files changed, 28 insertions(+), 8 deletions(-) diff --git a/Assets/PinAnimator.cs b/Assets/PinAnimator.cs index dd035ff09..b4d6dd2ec 100644 --- a/Assets/PinAnimator.cs +++ b/Assets/PinAnimator.cs @@ -1,4 +1,4 @@ -using CollectionExtensions; +using System; using UnityEngine; public class PinAnimator : AugmentAnimator @@ -31,6 +31,18 @@ public override void OnReload(GunStats stats) { } public override void OnFire(GunStats stats) { + #region Fix for specific bug after weaponswitching + try + { + var test = transform.localPosition; + } + catch (NullReferenceException) + { + Debug.LogWarning($"Ignoring nullref in {nameof(PinAnimator)}:OnFire"); + return; + } + #endregion + if (playAudio) PlayCockingSound(); transform.localPosition = Vector3.zero; diff --git a/Assets/Scripts/Augment/AugmentImplementations/BoomBardierAnimator.cs b/Assets/Scripts/Augment/AugmentImplementations/BoomBardierAnimator.cs index 35baacde3..b47f980ae 100644 --- a/Assets/Scripts/Augment/AugmentImplementations/BoomBardierAnimator.cs +++ b/Assets/Scripts/Augment/AugmentImplementations/BoomBardierAnimator.cs @@ -1,5 +1,3 @@ -using System.Collections; -using System.Collections.Generic; using UnityEngine; public class BoomBardierAnimator : AugmentAnimator @@ -25,16 +23,26 @@ public override void OnReload(GunStats stats) public override void OnFire(GunStats stats) { - animator.SetTrigger("Fire"); - ammo = stats.Ammo; - OnShotFiredAnimation?.Invoke(); - OnAnimationEnd?.Invoke(); + try + { + animator.SetTrigger("Fire"); + ammo = stats.Ammo; + OnShotFiredAnimation?.Invoke(); + OnAnimationEnd?.Invoke(); + } + catch (System.NullReferenceException) + { + // Avoids specific issue that only appears in build. + Debug.LogWarning($"Ignoring nullref in {nameof(BoomBardierAnimator)}:OnFire"); + return; + } } - + // Also called by animator public void VisualizeAmmoCount() { for (int i = 0; i < dynamites.Length; i++) + // TODO nullref here dynamites[i].enabled = ammo - 1 > i; } }