- Home /
how to start coroutines in the update method?
hello! I was wondering if there were any way to start a coroutine in the update method using something like yield return StartCoroutine("reload");
but I would like to declare this in the update method in an if statement.... however, the problem is the update method "cannot be an iterator block because 'void' is not an iterator interface type" and I can't fix this because Update can not be declared using IEnumerator which is what you usually do for coroutines. please help! here is the compile error i am getting:
error CS1624: The body of 'RayCast.Update()' cannot be an iterator block because 'void' is not an iterator interface type
here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RayCast : MonoBehaviour
{
public ParticleSystem MuzzleSmoke;
public ParticleSystem MuzzleFlash;
public int Bullets = 500;
public bool CanFire = true;
Camera cam;
private void Start()
{
CanFire = true;
cam = Camera.main;
}
void Update()
{
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
if (Input.GetMouseButton(0))
{
if (Bullets <= 0)
{
CanFire = false;
}
if (CanFire == true)
{
Bullets -= 1;
MuzzleFlash.Play();
MuzzleSmoke.Play();
if (Physics.Raycast(ray, out RaycastHit hit))
{
hit.collider.gameObject.transform.GetComponent<EnemyHealth>().HEALTH -= 1f;
}
}
if (Input.GetKeyDown(KeyCode.R))
{
if (Bullets <= 0)
{
yield return StartCoroutine("reload");
}
}
}
IEnumerator reload()
{
yield return new WaitForSeconds(5);
Bullets += 500;
CanFire = true;
}
}
}
Just do StartCoroutine("reload");
see if it works
Answer by Mrpxl · Jun 08, 2021 at 09:28 AM
To call a coroutine, you must call StartCoroutine("MyCoroutine")
or even StartCoroutine(MyCoroutine())
.
yield return StartCoroutine("reload");
Won't work. See Coroutines
Answer by glennMediaMonks · Jun 08, 2021 at 09:14 AM
" yield return " wont do anything in your Update loop, the yield command is specificly only useable inside the IEnumerator
Answer by WerewoofPrime · Jun 15, 2021 at 09:01 PM
the yield return StartCoroutine("reload");
works perfectly, just not in the Update method because Update cannot be IEnumerator... will StartCoroutine(MyCoroutine())
work in functions that are not IEnumerator?