Last active
May 6, 2019 22:17
-
-
Save SenpaiRar/d529faa11fd0f49a4bcfc38687ace219 to your computer and use it in GitHub Desktop.
The Crate Populator handles placing crates around the map.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
public class Crate_Populator : MonoBehaviour | |
{ | |
//This list holds the crate prefabs we can spawn. | |
public List<GameObject> CrateSpawnables = new List<GameObject>(); | |
//This variables tells the script how many crates to spawn in the game world | |
public int CratesToSpawn; | |
//Scale controls how the corresponding pixels in the image are then made into coordinates in the gamewor;d | |
public float Scale; | |
//This is the noise map the script uses to check whether the crate can be spawned in a certain position | |
public Texture2D SpawnMap; | |
//This is the list of crates we've already spawned | |
public List<GameObject> SpawnedGameObjects = new List<GameObject>(); | |
//We create a list that gives us the random positions to spawn crates at | |
public List<Vector3> SpawnVectors() | |
{ | |
List<Vector3> returnList = new List<Vector3>(); | |
//we make a loop that iterates as many times we need crates | |
for (int i = 0; i < CratesToSpawn;) | |
{ | |
//we generate two random numbers which is a random pixel on the noise map imae | |
int x = Random.Range(0, SpawnMap.width); | |
int y = Random.Range(0, SpawnMap.height); | |
//We check if that pixel is white using GetPixel() | |
if(SpawnMap.GetPixel(x,y).grayscale < 0.1f) | |
{ | |
//If it is, we add to our list of positions a Vector3 with our x and y being scaled, and setting the x and z components | |
returnList.Add(new Vector3(x/Scale, 0, y/Scale)); | |
//We then add 1 to i to keep the loop going | |
i++; | |
} | |
} | |
return (returnList); | |
} | |
public void Crate_Populate() | |
{ | |
//We make a list of Vector3s with holds the random positions | |
List<Vector3> CrateSpawnVectors = SpawnVectors(); | |
//We go through the list, doing the same thing as before of spawning the objects and adding them to a list. | |
foreach (Vector3 x in CrateSpawnVectors) | |
{ | |
GameObject z = Instantiate(CrateSpawnables[Random.Range(0, CrateSpawnables.Count)], x, Quaternion.Euler(0, Random.Range(0, 360), 0)) as GameObject; | |
SpawnedGameObjects.Add(z); | |
} | |
} | |
public void DestroyAllObjects(){ | |
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