IEnumerator & CoRoutine in C# for Unity

Karuna Ketan
2 min readDec 18, 2022

I learned about IEnumerator & CoRoutine in Unity…

14th Programs:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public bool _disableMovement = false;
// Our components
Rigidbody2D _rb; // Create the container for our Rigidbody2D

// Our fields related to movement
float _moveHorizontal; // Get horizontal input
float _moveSpeed = 60f; // Out movespeed
void Start()
{
// Assign the Rigidbody2D to our container
_rb = gameObject.GetComponent<Rigidbody2D>();
}
void Update()
{
// Assign the player input
_moveHorizontal = Input.GetAxisRaw("Horizontal");
}
void FixedUpdate()
{
if (!_disableMovement)
{
MovePlayer();
}
}
// Create the method for player movement
void MovePlayer()
{
if (_moveHorizontal != 0) // Check for player input
{
_rb.AddForce(new Vector2(_moveHorizontal * _moveSpeed, 0f));
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerTeleport : MonoBehaviour
{
PlayerController _playerController;
[SerializeField] GameObject _teleportLocation;

Coroutine _coroutine;

private void Start()
{
_playerController = GetComponent<PlayerController>();
}

// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
_coroutine = StartCoroutine(TeleportDelay());
}
if (Input.GetKeyDown(KeyCode.W))
{
// StopAllCoroutines();

StopCoroutine(_coroutine);
}
}

IEnumerator TeleportDelay()
{
_playerController._disableMovement = true;
// yield return null;
yield return new WaitForSeconds(3.5f);
gameObject.transform.position = _teleportLocation.transform.position;
yield return null;
_playerController._disableMovement = false;
}
}

From above program:

IEnumerator TeleportDelay()
{
_playerController._disableMovement = true;
// yield return null;
yield return new WaitForSeconds(3.5f);
gameObject.transform.position = _teleportLocation.transform.position;
yield return null;
_playerController._disableMovement = false;
}
  • IEnumerator TeleportDelay() is a method that allows to skip frames inside the game…
yield return new WaitForSeconds(3.5f);
  • After pressing Space it will wait for 3.5s and then further steps will be executed…

That’s all…Thank you for reading😉:)

click here to follow me in LinkedIn for more updates…

click here to follow me in GitHub for more updates…

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Karuna Ketan
Karuna Ketan

Written by Karuna Ketan

Game Designer and Developer | Unity, Unreal Engine, Blender

No responses yet

Write a response