I need help with this. I’m super new to Unity and scripting and I need to make it so a game has about 5 different colored targets (all worth different points) that must have a 10% chance of spawning ever 0.5 seconds. How would one go about doing this do you think? Any tips and tricks are helpful. Thanks!
Untested code, but something like this:
function Start() {
InvokeRepeating("SpawnChance", 0.5, 0.5);
}
function SpawnChance() {
if (Random.Range(0,10) == 0)
// Spawn something
}
You could have multiple different spawn changes SpawnChangeRed(), SpawnChangeBlue()…
And use InvokeRepeating() on each.
Each of these features must be separated and understood individually:
1create a timer
2create a “decision” based on a percentage (10%)
3spawn an object
lets start with the timer… luckily Unity gives a good method for this one, InvokeRepeating
the link gives a pretty good example to get you where you want… (no need to put this inside Start, as the previous answer suggests…)
next for the “10% chance”:
we can simply use a random number for now:
if(Random.Range(0,10) == 5)
for example, would be all you need
then for the spawn, use Instantiate… so here’s a sample script (javascript):
var myObjects : GameObject[] = new GameObject[5];
InvokeRepeating(SpawnStuff,0,.5);
function SpawnStuff(){
if(Random.Range(0,10) == 5){
var getRandomObject = Random.Range(0,myObjects.length);
Instantiate(myObjects[getRandomObject],transform.position,transform.rotation);
}
}
this example still spawns everything in the same place though, you will need to figure out how to stagger the position (you can use a similar random number within the desired range, on the position var x,y, or z position…
by the way, myObjects is an ARRAY, for now you can view it in the inspector and add your objects to its slots there… this will give you an idea of what an array is, and why it is so useful!