- Home /
How to use a float value from coroutine 1 and use in coroutine 2?
Hi,
I have two scripts that are attached to different objects. Script 1 with Coroutine 1 are attached to a prefab. Script 2 and Coroutine 2 are attached to an empty spawner object.
Coroutine 1 has a variable called time. It randomly chooses a number and stores into that variable, like ex. time = 3. What I need is to use that variable in Coroutine 2 so that I can yield WaitForSecond(time).
The problem is that I`m able to set a reference to the Script 1 and reference the variable time. But the Script 2 cannot use that value. When I Debug.Log(time) in the Script 2 it says 0 all the time. However, if I debug it in the Script 1 even outside the coroutine function it shows the right number in the console.
How can I make it work in the Script 2 as well?
Script 1:
IEnumerator Coroutine1(){
time = Random.Range (1f, 3f);
Script 2:
IEnumerator Coroutine2(){
while (true) {
Rigidbody2D hazard = Instantiate (hazardBlock, hazardPosition, Quaternion.identity);
Debug.Log(time); // this shows 0 all the time
yield return new WaitForSeconds (time); // this is 0 all the time
Thank you.
@Eric5h5 $$anonymous$$ay I ask for your help? I know that you`re very good at coroutines.
Answer by unit_nick · Oct 17, 2017 at 08:00 AM
dunno what you're doing wrong. the following works
public float time;
private void Start()
{
time = 0;
StartCoroutine(Coroutine1());
StartCoroutine(Coroutine2());
}
IEnumerator Coroutine1()
{
while (true)
{
time = Random.Range(1f, 3f);
yield return new WaitForSeconds(time);
}
}
IEnumerator Coroutine2()
{
while (true)
{
//Rigidbody2D hazard = Instantiate(hazardBlock, hazardPosition, Quaternion.identity);
Debug.Log(time);
yield return new WaitForSeconds(time);
}
}
You missed the part in the beginning where I said these are 2 different scripts attached to 2 different game objects (empty object and prefab).
nah not really. I simply answered in context to your question. this also works (when in separate scripts) remember that i'm answering on the basis that you have said
I`m able to set a reference to the Script 1 and reference the variable time.
so I'm demonstrating that any correctly referenced variable will work
using System.Collections;
using UnityEngine;
public class Script1 : $$anonymous$$onoBehaviour
{
public static float time;
void Start()
{
time = 0;
StartCoroutine(Coroutine1());
}
IEnumerator Coroutine1()
{
while (true)
{
time = Random.Range(1f, 3f);
yield return new WaitForSeconds(time);
}
}
}
public class Script2 : $$anonymous$$onoBehaviour
{
void Start()
{
StartCoroutine(Coroutine2());
}
IEnumerator Coroutine2()
{
while (true)
{
Debug.Log(Script1.time);
yield return new WaitForSeconds(Script1.time);
}
}
}