Skip to content

Instantly share code, notes, and snippets.

@SenpaiRar
Created May 6, 2019 21:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SenpaiRar/c07222d8ef98af12017065df42eecff8 to your computer and use it in GitHub Desktop.
Save SenpaiRar/c07222d8ef98af12017065df42eecff8 to your computer and use it in GitHub Desktop.
This populator places object that should be placed in a uniform, random distribution, unlike the Environment populator which uses a noise map.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Detail_Populator : MonoBehaviour
{
//These two variables control how far the objects could potentially be placed.
//Ex. If these two variables were set to 20, the the farthest an object could be placed is at (20,0,20)
public float EndRangeX;
public float EndRangeY;
//Because this populator doesn't use a noise map to spawn objects, we need to specify how many objects the populator has to spawn
public int NumberofObjectsToSpawn;
//This is the list of prefab/gameobjects the populator could spawn
public List<GameObject> spawnGameObjects = new List<GameObject>();
//We make a list to manipulate the gameobjects we have spawned. We make sure to hide it in the editor because there's no point in showing it
[HideInInspector]
public List<GameObject> spawnedGameObjects = new List<GameObject>();
//Similar to the environment populator, we define a function that gives us a list of Vector3s positions
public List<Vector3> GetSpawnVectors(){
//we make a list to add on Vector3s for
List<Vector3> NewList = new List<Vector3>();
//We make a loop that will iterate depending on how many objects we want to spawn
for(int i=0; i < NumberofObjectsToSpawn; i++){
//We create a new vector with the x and z components having a random number between 0 and the preivously specified upper bounds
//We then add that Vector3 to the list
NewList.Add(new Vector3(Random.Range(0, EndRangeX), 0, Random.Range(0, EndRangeY)));
}
//We make the function give that list of Vector3
return (NewList);
}
//This is the function that actually spawns our gameobjects
public void Spawn_Objects(){
//We create a vector3 list and set it to GetSpawnVectors() which gives us the random positions
List<Vector3> SpawnVectors = GetSpawnVectors();
//We go through that list, setting the Vector3 we're on as x
foreach (Vector3 x in SpawnVectors){
//Similar to before, we create a gameobject and set it to a copied randomly selected object from that list, and then add it to a list.
GameObject y = Instantiate(spawnGameObjects[Random.Range(0, spawnGameObjects.Count)], x, Quaternion.Euler(0, Random.Range(0,360), 0)) as GameObject;
spawnedGameObjects.Add(y);
}
}
public void Destroy_Objects(){
foreach(GameObject x in spawnedGameObjects){
DestroyImmediate(x);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment