Trying to get a platform to fall after touching it for a total of 5 seconds in C#

51 Views Asked by At

I'm attempting to make a falling animation activate after my Player steps on a platform for a certain amount of time. I'm trying to do this in Unity with c#.

I've tried to use a coroutine to execute code over time but it does not seem to work in an on trigger enter method. I've also tried to use a bool and a timer variable to see if the player is touching for set amount of seconds.

IEnumerator OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Player")
        {
            yield return new WaitForSeconds(5);
            myAnimationController.SetBool("FallWhenTouched", true);
            Debug.Log("It Worked");
            Debug.Log(other.gameObject.name);

            
        }
    }
2

There are 2 best solutions below

1
Agni On

I would just use standard Invoke function with time delay.

private void OnTriggerEnter(Collider other)
{
    if (other.CompareTag("Player")
    {
        Invoke(nameof(ActivateFall), 5.0f);
    }
}
private void ActivateFall() {
  myAnimationController.SetBool("FallWhenTouched", true);
}
0
Everts On

One thing to consider in your case is to prevent multiple calls for the drop. If player jumps on the platform and then jumps again, it would trigger the drop twice. If you use an animation for the drop, then the second call would reset the platform for drop animation.

Let's see with coroutine since you started with that:

private bool m_dropPlatform;
private void OnTriggerEnter(Collider other)
{
    if (other.CompareTag("Player") && !m_dropPlatform)
    {
        m_dropPlatform = true;
        StartCoroutine(DropPlatformSequence());
    }
}

IEnumerator DropPlatformSequence()
{
    yield return new WaitForSeconds(5);
    myAnimationController.SetBool("FallWhenTouched", true);
}