IEnumerator & CoRoutine in C# for Unity
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…