I’m having an issue with generating asteroids in random positions, based on the random number generator provided in unity. The rest of the Start() function appears to be working properly, as 99 randomly sized asteroids are being created in the scene, but they are all stacked on top of each other, apparently in the same position. I’ve tried to run the code with and without the Random.InitState(System.Environment.TickCount) and get the same result either way.
Can anyone tell me what the problem is? Code (C#) is attached below.
Thanks!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AsteroidGenerator : MonoBehaviour
{
//meshes and textures that are loaded at run time
public Mesh asteroid1;
public Mesh asteroid2;
public Mesh asteroid3;
public Material lightGrey;
public Material darkGrey;
public Material rockTexture;
// Start is called before the first frame update
void Start()
{
Random.InitState(System.Environment.TickCount);
//function creates 99 asteroids of random size
int i, counter = 0;
for(i = 0; i < 100; ++i)
{
//create a new game object, mesh, and material to attach to it
GameObject theAsteroid = new GameObject("Asteroid" + i);
Mesh asteroid;
Material thisMaterial;
//position where the game object will be placed (random)
Vector3 pos = generateRandomPos();
//depending on count, set mesh and material components
if (counter == 0)
{
thisMaterial = lightGrey;
asteroid = Instantiate(asteroid1, pos, Quaternion.identity);
++counter;
}
if(counter == 1)
{
thisMaterial = darkGrey;
asteroid = Instantiate(asteroid2, pos, Quaternion.identity);
++counter;
}
else
{
thisMaterial = rockTexture;
asteroid = Instantiate(asteroid3, pos, Quaternion.identity);
counter = 0;
}
//assign mesh and material components to gameobject
theAsteroid.AddComponent<MeshFilter>();
theAsteroid.AddComponent<MeshRenderer>();
theAsteroid.GetComponent<MeshRenderer>().material = thisMaterial;
theAsteroid.GetComponent<MeshFilter>().mesh = asteroid;
//set size of asteroid
theAsteroid.transform.localScale = new Vector3(Random.Range(5f, 20f), Random.Range(5f, 20f), Random.Range(5f, 20f));
//add rigidbody and mesh collider
theAsteroid.AddComponent<Rigidbody>();
Rigidbody rb = theAsteroid.GetComponent<Rigidbody>();
rb.useGravity = false;
MeshCollider coll = theAsteroid.GetComponent<MeshCollider>();
theAsteroid.transform.parent = this.transform;
}
}
//generates random position based on seed
Vector3 generateRandomPos()
{
//Random.InitState(time);
float x = Random.Range(-500, 500);
float y = Random.Range(-100, 100);
float z = Random.Range(-700, 700);
return new Vector3(x, y, z);
}
}