Increase variable for a few seconds

Hi,

I want to increase the speed of my character by 5 (in this example) when I collide with my power up and then return back to normal after a set time.

Now, this works but as I want it to.

The way it works now is…
I collide, speed goes up but the game object is still there. It is only deleted once the yield is finished. I heard I cannot delete the object until the process is over other it doesn’t work.

Its not really a power up if it isn’t removed from the scene.

To get around this, I removed the Sprite Rendered. The object becomes invisible which works I guess. But now, during the process, if i touch this invisible object, the speed increase as many times as I touch it till it is deleted…

Here is my code:

void OnCollisionEnter2D(Collision2D other)
	{
		if (other.gameObject.tag == "Player")
		{

			PlayerMovement.movespeed += 5;
			StartCoroutine(speedTime());
			GetComponent<SpriteRenderer>().enabled = false;
		}
	}
	
	IEnumerator speedTime ()
	{
		yield return new WaitForSeconds(3);
		revertSpeed();
		Destroy(gameObject);


	}
	
	void revertSpeed ()
	{
		PlayerMovement.movespeed = 2;
	}

What is the best way to get around this?

Thanks

I guess if you just remove any visual and physical interaction, you can keep your object there until destruction

void OnCollisionEnter2D(Collision2D other)
{
   if (other.gameObject.tag == "Player")
   {
     renderer.enabled = false;    // Remove visual
     collider.enabled = false;    // Remove physical
     PlayerMovement.movespeed += 5;
     StartCoroutine(speedTime());
     GetComponent<SpriteRenderer>().enabled = false;
   }
}

the easiest way I can think of is to have a bool variable that is off initially and then turned on after collision, it works for what you want and you can reenable it for respawning power-ups.

private bool tripped = false;

void OnCollisionEnter2D(Collision2D other)
    {
       if (other.gameObject.tag == "Player" && !tripped)
       {
         tripped = true; // this stops OnCollisionEn.... from running again
         PlayerMovement.movespeed += 5;
         StartCoroutine(speedTime());
         GetComponent<SpriteRenderer>().enabled = false;
       }
    }
 
    IEnumerator speedTime ()
    {
       yield return new WaitForSeconds(3);
       revertSpeed();
       Destroy(gameObject);
 
 
    }
 
    void revertSpeed ()
    {
       PlayerMovement.movespeed = 2;
    }`