I’ve attached a script to my player character that increases move speed once the player collects a certain item. First part is fine, player collects the item then sets off like his butt is on fire. However after 5 seconds I want the effect to wear off and here’s where I’m getting my problem.

(just added a Dubug.Log to see if the coroutine is being called and it is so the problem(I’m guessing) is with my WaitForSeconds code)

C# script -

using UnityEngine;
using System.Collections;

public class SpeedBoostActivate : MonoBehaviour
{

	public GameObject SpeedIcon;
	public float walkSpeed = 7; // regular speed
	public float runSpeed = 20; // run speed
	private CharacterMotor chMotor;

	private bool Supersonic = false;
	
	
	// Use this for initialization
	void Start () 
	{
		chMotor =  GetComponent<CharacterMotor>();
	}


	void Update()
	{
	
	}


	void OnTriggerEnter(Collider collider)
	{ 
		float speed = walkSpeed;

		if(collider.gameObject.name == "SpeedBooster")
		{
			speed = runSpeed;
			Supersonic = true;
		}

		chMotor.movement.maxForwardSpeed = speed; // set max speed

		StartCoroutine(ResetRunSpeed());

	}


		IEnumerator ResetRunSpeed()
		{
			Debug.Log ("This is working so far"); //Add this to see if coroutine is being called?

			//yield return new WaitForSeconds(5f);

			if(Supersonic == true)
			{
				yield return new WaitForSeconds(5f);
				walkSpeed = 7;
				Supersonic = false;
			}
		}

}

What am I doing wrong? As usual all help is greatly appreciated !

???

  • Do a StartCoroutine, when you trigger the speedbooster, and set runspeed
  • Do a StopCoroutine and set walkspeed, if not

Use this for the coroutine

IEnumerator ResetRunSpeed()
{
  yield return new WaitForSeconds(5f);
  walkSpeed = 7;
}

My guess is that the coroutine is working correctly, but that the rest of your logic is wrong.
Why in the coroutine are you setting walkSpeed = 7; (when nothing has changed it anyway? And what’s the point of setting superSonic when nothing else relies on it? And you never set the character motor max speed back to walkSpeed except for when it triggers something.

My guess is that you wanted to do something more like this:

using UnityEngine;
using System.Collections;
public class SpeedBoostActivate : MonoBehaviour
{
    public GameObject SpeedIcon;
    public float walkSpeed = 7; // regular speed
    public float runSpeed = 20; // run speed
    private CharacterMotor chMotor;

	// Use this for initialization
	void Start ()
	{
		chMotor = GetComponent<CharacterMotor>();
	}
	
	void OnTriggerEnter(Collider collider)
	{
		if(collider.gameObject.name == "SpeedBooster")
		{
			chMotor.movement.maxForwardSpeed = runSpeed;
			StartCoroutine(ResetRunSpeed());
		}
	}
	IEnumerator ResetRunSpeed()
	{
		Debug.Log ("This is working so far"); //Add this to see if coroutine is being called?

		yield return new WaitForSeconds(5f);
		chMotor.movement.maxForwardSpeed = walkSpeed;
	}
}