WaitForSeconds() not Waiting.

I’m trying to make a death-run type game. I’ve tried multiple ways of fixing it which have not worked.
What is happening is the WaitForSeconds() function is not working before the Disable. I am new to C# and Unity so i don’t really have a massive clue about how to fix it. Note: i am not sure what topic to put this under.

public static IEnumerator WaitTwoSeconds()

{

    yield return new WaitForSeconds(2);
}
void OnTriggerEnter(Collider otherObject)
{
    if (otherObject.gameObject.CompareTag("Player"))
    {
        WaitTwoSeconds();
        gameObject.SetActive(false);
        }
    }
}

Hi there @InvictusActuary

You cannot use WaitForSeconds() in this manner, it is meant to be done asynchronously.

The way to achieve what you want is by changing WaitTwoSeconds() to disable the current GameObject as you are now, rather than leaving it to OnTriggerEnter()to disable it.

For context in the example below, I have changed the name of WaitTwoSeconds() to DisableSelfWithDelay().

Example:

 public IEnumerator DisableSelfWithDelay()
 {
     yield return new WaitForSeconds(2);
     gameObject.SetActive(false);

 }
 void OnTriggerEnter(Collider otherObject)
 {
     if (otherObject.gameObject.CompareTag("Player"))
     {
         StartCoroutine(DisableSelfWithDelay());
     }
 }

Hope this helps!

Edit: the method should not be static for what you’re trying to do, so I have changed that in the example to an instance method.