- Home /
Will calling a Coroutine every time the player shoots an object a bad way to program?
I am making a game kind of like Call Of Duty Zombies. I have it so that if the player shoots the zombie with a bullet, it only gives them 10 points, but if the player kills a zombie with a bullet, it gives them 60 points. Here is the code I made for that, and I am wondering if it is an efficient way of doing it, because idk if Coroutines are expensive. If I go this route, then this Coroutine will run every time the player shoots an object.
(just to clarify the coding a bit, when a zombie is alive, it is tagged with "Enemy", and when they die they are tagged with "Untagged").
Answer by luiscmendez · Jul 13, 2018 at 11:13 PM
Generally yes. But it can get pretty messy if you have multiple coroutines running without ever stopping them. Using a Coroutine is a lot better than using the Update loop. But It's good practice to keep track of a Coroutine so that you can start it and stop it at any given time without creating a new one. In your case you may also want to cache your WaitForSeconds so that it's not creating a new one every single time you run it.
It might be better if you use the Coroutine like an Update loop and leave it running from the start. Then all your logic checks happen within that loop rather than starting the loop every time the player shoots. So you would essentially just keep checking whether or not the player has shot, then run your logic based off of that value rather than running a Coroutine after the player has shot.
Here's a quick example:
using UnityEngine;
using System.Collections;
using UnityEngine.Events;
public class AwardPoints : MonoBehaviour
{
public float delayTime = 0.1f;
private IEnumerator currentProcess;
private WaitForSeconds cachedDelay;
private void Start()
{
cachedDelay = new WaitForSeconds(delayTime);
}
private void StartCoroutine()
{
if (currentProcess != null)
{
StopCoroutine(currentProcess);
}
currentProcess = Process();
StartCoroutine(currentProcess);
}
private void StopCoroutine()
{
if (currentProcess != null)
{
StopCoroutine(currentProcess);
currentProcess = null;
}
}
private IEnumerator Process()
{
while (true)
{
if(hit.collider.transform.root.tag.Contains("Enemy"))
{
yield return cachedDelay;
if(hit.collider.transform.root.tag.Contains("Untagged"))
{
//Do stuff
}
else
{
//Do other stuff
}
}
yield return null;
}
}
}
So every time you want to run this check you call StartCoroutine() which will stop the current process if it's still running, and start a new one after that. Or just start a new one if one does not exist. Let me know if anything isn't clear.
It seems to work except that when I shoot the zombie with one bullet, it does give me 10 points, but it keeps giving me 10 points until I kill the zombie.
Your answer
