- Home /
How do I randomize 5 prefabs on Scene loaded?
I just woder how do I randomize for example 5 prefabs: Thunderbolt, Mackey x270, CM lazer, Pashasprayer, Badass shotgun? I want it to be 50% chance of thunderbolt 15% chance of Mackey x270 5% chance of pashasprayer 29% chance of badass shotgun and 1% chance of CM Lazer? I just want them equipped with a random scrip, don't care wich one. I'm just gonna use one gun.
Thank you for your time
It's possible someone might come along and write something for you, you will get better responses if you at least attempt to create the code yourself... if you do so, post it here with any issues and you will probably get some advise.
I'm still not that good with coding, Pretty basic. I'm just asking here to get a clue about what to write
Well, i would suggest you take a stab at it first, this is how most of us have learned, through trial and error..error...error, win?
you already know you need at least 5 prefabs, which means you need an collection or array of either GameObjects/Transforms to be set in the inspector.
The name can be set on the game object if you want. the rest is just math and association.
Answer by Nick4 · Jun 10, 2014 at 02:21 PM
I'm not good at calculating possibilities but let me take a shot.
public class Class1 : MonoBehaviour
{
// Assign your prefabs to this array in the inspector panel
public GameObject[] guns = new GameObject[5];
// Weapon that will be assigned to, after required calculations
private GameObject currentWeapon;
void Start()
{
currentWeapon = RandomWeapon()
}
// Returns a random weapon based upon a random int variable.
private GameObject RandomWeapon()
{
int random = Random.Range(1, 100);
if(random <= 50)
{
return SelectWeapon("thunderbolt");
}
else if(random > 50 && random <= 65)
{
return SelectWeapon("mackey");
}
else if(random > 65 && random <= 70)
{
return SelectWeapon("sprayer");
}
else if(random > 70 && random <= 99)
{
return SelectWeapon("shotgun");
}
// which leaves us the remaining %1, 100.
else
{
return SelectWeapon("cmLazer");
}
}
// Finds and returns the requested weapon by name
private GameObject SelectWeapon(string weaponName)
{
for(int i = 0; i < guns.Length; i++)
{
if(guns[i].name == weaponName)
{
return guns[i];
}
}
}
}
I'm sorry if there are typos in my code because I have directly written these here. Note that it's probably not an efficient way to return a random variable from an array based on given percentages. I just wanted to write some code.