- Home /
Setting float variable to an Array value
I have objects that instantiate at every random Array value and i want to do something if a specific Array value is selected.
I can't find a way to use Array in an if statement to check if a certain Array was selected, so is there a way to set my float variable to an Array value?
public float[] spawnTime;
public float spawnValue;
IEnumerator Spawner()
{
yield return new WaitForSeconds(spawnTime[Random.Range(0, 5)]);
Instantiate(object, 1f, 1f), Quaternion.identity);
spawnValue = **// the random selected spawnTime.**
if (spawnValue == **// the random selected spawnTime.**)
{
Debug.Log ("Do something");
}
}
Answer by unity_HTr7mOeTIRzvVA · Jun 10, 2021 at 09:57 PM
there's many ways to get that random array. First is to store the index, second is store the float value.
int randomIndex = Random.Range(0, spawnTime.Length);
yield return new WaitForSeconds(spawnTime[randomIndex]);
if(spawnValue == spawnTime[randomIndex]){
// yeah
}
or
float randomFloat = spawnTime[Random.Range(0, spawnTime.Length)];
yield return new WaitForSeconds(randomFloat);
if(spawnValue == randomFloat){
// yeah
}
note that spawnTime.Length is automatic for the entire spawnTime array, you don't need to manually type the specific number like "5" in your code sample.
Your answer
Follow this Question
Related Questions
Pick between two floats 2 Answers
"Talent Tree" global yes/false var and int? 3 Answers
Random Float Variable 2 Answers
String Access problem 1 Answer
convert object to float 2 Answers