create a random integer then use that integer in two seperate functions
Hello I am trying to have a number randomly generated, then be able to call the same number in two separate functions. I want the number to change when the function that is generating the number is called, but want to be able to keep the number the same when the two functions that call the number use it.
public GameObject[] groups;
public void getGroup()
{
int z = Random.Range (0, groups.Length);
}
public void spawnNext()
{
//spawn on board when function is called
Instantiate (groups [z], transform.position, Quaternion.identity);
}
public void previewSpawn()
{
//spawn in preview window when function is called
Instantiate (groups [z], transform.position, Quaternion.identity);
}
Answer by saschandroid · Nov 24, 2015 at 07:07 AM
public GameObject[] groups;
int z = 0;
public void getGroup()
{
z = Random.Range (0, groups.Length);
}
Answer by pekalicious · Nov 24, 2015 at 02:09 PM
You are declaring and storing your variable "z" in a method. That means that as soon as that method completes executing, "z" will no longer exist.
You need to declare "z" in the script level, so that all methods in that script can access it. saschandroid's answer does just that.
Answer by xylofiso · Nov 24, 2015 at 07:45 PM
Thanks, now if I can just figure out how to have both of these methods called based on this Tetris tutorial from Noobtuts.com I am following XD
I'm really good at breaking Unity and C# scripts ha.