slow effect time stacking on player if hit by slow multiple times

im very new to unity and cant find an answer on google. I have an orb sent by an enemy that slows the player if it hits them. what I cant figure out is if a second orb hits the player I want it to slow them even longer. currently it just runs the normal slow duration and ends. also for some reason even after the slow ends the player is immune to being slowed again for a second or two.
sorry if this is the wrong place to ask, its my first time posting here. if theres a correct place to ask questions please point me there ty!
heres my code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerSlowed : MonoBehaviour
{
    public bool isSlowed = false;

    private float defSpeed;


    private void Start()
    {
        defSpeed = GetComponent<PlayerController>().moveSpeed;
    }


    void Update()
    {
        if (isSlowed)
        {
            GetComponent<PlayerController>().moveSpeed = 2.5f;
          
            StartCoroutine(SlowTimer());

        }
    }

    IEnumerator SlowTimer()
    {
        yield return new WaitForSeconds(2.5f);
        GetComponent<PlayerController>().moveSpeed = defSpeed;
        isSlowed = false;
    }
}

Just decrease the speed instead of hardcoding it, and all this code can be simplified a lot, and with better performance:

public class PlayerSlowed : MonoBehaviour
{
    // You can tweak this in the Editor to get the result you want
    [SerializeField]
    private float speedDecreaseAmount = 0.5f;

    private PlayerController _playerController;

    private void Start()
    {
        // It's a good idea to get the PlayerController once only and cache it
        _playerController = GetComponent<PlayerController>();
    }

    public void SlowPlayer()
    {
        // We don't want the player to stop moving completely?
        if (_playerController.moveSpeed <= 0.1)
            return;

        // Decrease the speed by speedDecreaseAmount (0.5 by default)
        _playerController.moveSpeed -= speedDecreaseAmount;
  
        StartCoroutine(SlowTimer());
    }

    private IEnumerator SlowTimer()
    {
        yield return new WaitForSeconds(2.5f);

        // We re-add back the amount we removed (speedDecreaseAmount)
        _playerController.moveSpeed += speedDecreaseAmount;
    }
}

And to slow the player, you just need to do:

GetComponent<PlayerSlowed>().SlowPlayer();
1 Like

oh that makes more sense thanks! also thanks for the extra tips inside that actually helps a ton!!

1 Like