Turning a int into a possibility of 19 different outcomes
As the question says. I have a script currently working as such. If said number is equal to another. Do something. Code: void ConvertToPrefab(int[] convert) { toSpawn = new GameObject[convert.Length]; for (int i = 0; i < convert.Length; i++) { if (convert[i] == 0) { toSpawn[i] = prefabs.cubes[0]; } else if (convert[i] == 1) { toSpawn[i] = prefabs.cubes[1]; } } and so on. How might I go about just having a few lines instead of somewhere of about 80? This would really help since this code is used often and can be ran with about 500 different integers at once. I feel like this is causing a little hiccup and would like to find a better solution.
Answer by Commoble · Mar 01, 2017 at 07:48 PM
Firstly, you can make your code samples easier to read here by using the Code Sample button just above the text entry box, which preserves tabs and line breaks:
void ConvertToPrefab(int[] convert)
{
toSpawn = new GameObject[convert.Length];
for (int i = 0; i < convert.Length; i++)
{
if (convert[i] == 0)
{
toSpawn[i] = prefabs.cubes[0];
}
else if (convert[i] == 1)
{
toSpawn[i] = prefabs.cubes[1];
}
}
}
Secondly, I'm a little confused as to what you're trying to accomplish. The loop you have above can be simplified like this:
void ConvertToPrefab(int[] convert)
{
toSpawn = new GameObject[convert.Length];
for (int i = 0; i < convert.Length; i++)
{
toSpawn[i] = prefabs.cubes[convert[i]];
}
}
This is assuming your int[] convert array is a jumble of random integers in no particular pattern, all of which are valid indices for your prefab array. If this isn't what you're looking for, we'll need more details about what you have and what you're trying to do.
That worked but with slight modification, convert[i] needs to be ins$$anonymous$$d (convert[i]) unity thinks you are telling that array to do something other than tell information.
void ConvertToPrefab(int[] convert)
{
toSpawn = new GameObject[convert.Length];
for (int i = 0; i < convert.Length; i++)
{
toSpawn[i] = prefabs.cubes[(convert[i])];
}
}
Also, I have another void that is turning object names into integers. Is this possible without the same huge amount of code?
void ConvertToInt(GameObject[] convert) { for (int i = 0; i < convert.Length; i++) { if (convert[i].name == ("RedCube(Clone)")) { //Red Cube cubeId[i] = 0; }
{
{
Your answer
![](https://koobas.hobune.stream/wayback/20220612112215im_/https://answers.unity.com/themes/thub/images/avi.jpg)