Home > Blockchain >  Instantiate asteroid field with for loop
Instantiate asteroid field with for loop

Time:04-08

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MultiSpawner : MonoBehaviour
{
    public GameObject Asteroid;
    // Start is called before the first frame update
    void Start()
    {
        for (int i = 0; i < 20; i  ) {
            for (int j = 0; j < 20; j  ) {
                for (int k = 0; k < 20; k  ) {
                    Instantiate(Asteroid, new Vector3(j * 8, i * 8, k * 8), Quaternion.identity);
                }
            }
        }
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

Hello everyone! I need some help with this. I'm trying to instantiate an 'asteroid field' with basic cubes for now, but right now it creates a 20x20x20 field with cubes (which makes sense)

  1. How can I make it so inside of that 20x20x20 area, some cubes spawn while others don't (Reason for the 3-double for loop is because it's needed in the assignment)
  2. Or, if we completely disregard my code, how can I instantiate cubes in random places within a certain area?

CodePudding user response:

Read up on Unity’s Random class, UnityEngine.Random. This allow you to solve both this problem and other problems requiring randomness in the future.

At the top of your script file, include this with the other using lines:

using Random = UnityEngine.Random;

You can then use for example Random.Range(0f, 160f) to get a random float >= 0.0f and <= 160.0f, e.g. to be used as the coordinate of a Vector3. Or you can use Random.value (which returns a float >= 0.0f and <= 1.0f) to do something like this:

if( Random.value < 0.25f )
    Instantiate(Asteroid, new Vector3(j * 8, i * 8, k * 8), Quaternion.identity);

Which would give a 25% chance of that line executing.

Be aware that Random.Range(0, 160) (using ints, not floats) will return a random integer >= 0 (“inclusive”) and < 160 (“exclusive”). That is, it can return 0 but will never return 160. Conversely the float version could potentially return exactly 0f or exactly 160f (though the chances are small).

CodePudding user response:

for (int i = 0; i < 20; i  )
        {
        float randomX = Random.Range(0, 20);
        float randomY = Random.Range(0, 20);
        float randomZ = Random.Range(0, 20);
        Instantiate(Asteroid, new Vector3(randomX, randomY, randomZ), new Quaternion(0, 0, 0, 0));
        }

I think this does what you're asking. Just picks random x, y, and z values between 0 and 20 and instantiates 20 different Asteroid GameObjects.

  • Related