Delay Jump

Hello Unity Community,

I’m trying to create a slight delayed jump at 1.3 seconds after the player has collided with specific objects. For example, when the user collides with certain objects that have a tag called “Collision” and then they jump, it should take 1.3 seconds before the player jumps.

Here’s my code:

using UnityEngine;
using System.Collections;

public class MoveForward : MonoBehaviour {
	public float speed = 6.0F;
	public float jumpSpeed = 8.0F;
	public float gravity = 20.0F;
	private Vector3 moveDirection = Vector3.zero;	
	
	void Start () {
		AkSoundEngine.PostEvent("Play_FS_Running", gameObject);	
	}
	
	// Update is called once per frame
	void Update () {
		CharacterController controller = GetComponent<CharacterController>();
		 if (controller.isGrounded) {
			moveDirection = new Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"), 2);
			moveDirection = transform.TransformDirection(moveDirection);
			moveDirection *= speed;
			 if (Input.GetButton("Jump"))
			{
				moveDirection.y = jumpSpeed;
				AkSoundEngine.PostEvent("Play_Jump", gameObject);
			}
				
		}
		moveDirection.y -= gravity * Time.deltaTime;
		controller.Move(moveDirection * Time.deltaTime);	
	}
	void OnControllerColliderHit (ControllerColliderHit OtherObj) {
		if (OtherObj.collider.tag == "Collision")
         Debug.Log("We've collided"); 
       }
}

The line before ‘Debug.Log(“We’ve collided”);’ is where I need to put the proper code I believe. I’ve heard that I should look into coroutines but, from my understanding, a coroutine yields methods so it wouldn’t work with my current code. Maybe I’m wrong. What I need is to be pointed in the right direction. Any input is appreciated as I’ve been struggling with this problem for almost 2 months. Seriously.

Thank you for your time.

You’re right about the coroutine but I think you have to split it into a new routine. So at your debug.log statement do this

startcoroutine(myDelay());

Then your myDelay function as follows:

//myDelay function
IEnumerator myDelay()
{
yield return WaitForSeconds(1.3f);
//Whatever code you want to do, ie jump
}

Alternative would be use Invoke

Invoke("MyJumpRoutine",1.3F);