- Home /
C#, is this how you use a coroutine properly?
I'm trying to understand coroutines, so I tried to apply them to a little game.
The script works perfectly but I don't know if this is the proper way to use a coroutine. Is there any alternative to what I did?
using UnityEngine;
using System.Collections;
public class scriptEnemy : MonoBehaviour {
//Inspector variables
public Color[] shapeColor;
public int numberOfClicks = 2 ;
public float waitTime = 1f;
//Private variables
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(numberOfClicks <= 0)
{
Vector3 position = new Vector3(Random.Range(-9f, 9f), Random.Range(-5f, 5f), 0);
RespawnWaitTime();
RandomColor();
StartCoroutine(RespawnWaitTime());
transform.position = position;
numberOfClicks = 2;
}
}
//Used to hide the object for a certain amount of time
IEnumerator RespawnWaitTime()
{
renderer.enabled = false;
yield return new WaitForSeconds(waitTime);
renderer.enabled = true;
}
//used to change the material color of an objects
void RandomColor()
{
if(shapeColor.Length > 0){
float newColor = Random.Range (0f,(float)shapeColor.Length);
renderer.material.color = shapeColor[(int)newColor];
}
}
}
Answer by YoungDeveloper · Oct 01, 2013 at 08:48 PM
Considering if what interests you are basically these two blocks.
StartCoroutine(RespawnWaitTime());
and
IEnumerator RespawnWaitTime()
{
renderer.enabled = false;
yield return new WaitForSeconds(waitTime);
renderer.enabled = true;
}
Then yes, everything is super puper, if we are talking about code itself. But there's one thing, note that you are calling it from update function, so function RespawnWaitTime() will be called each frame. If you want to call only one instance of that function, check out this topic i gave answer for: http://answers.unity3d.com/questions/541018/wow-my-enemies-are-pretty-strong.html It's the same problem but the only difference it's in ongui and js.