Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- [System.Serializable]
- public class SpawnableAnimal
- {
- public string AnimalName;
- public int spawnChance;
- }
- public class AnimalSpawner : MonoBehaviour {
- public float maxSpawnRadius = 1000.0f;
- public float noSpawnRadius = 700.0f;
- public GameObject spawnedAnimal;
- public SpawnableAnimal[] spawnableAnimals;
- void Start () {
- System.Random rand = new System.Random();
- int randInt = rand.Next(0, 100);
- float startTime = randInt / 100;
- float repeatTime = randInt / 100;
- InvokeRepeating("ReadyToSpawn", startTime, (60.0f + repeatTime));
- }
- void ReadyToSpawn()
- {
- Debug.Log("Ready to spawn");
- bool canSpawn = true;
- GameObject[] players = GameObject.FindGameObjectsWithTag("Player");
- GameObject[] animals = GameObject.FindGameObjectsWithTag("Animal");
- for(int i = 0; i < players.Length; i++)
- {
- if (Vector3.Distance(this.transform.position, players[i].transform.position) > maxSpawnRadius)
- canSpawn = false;
- if (Vector3.Distance(this.transform.position, players[i].transform.position) < noSpawnRadius)
- canSpawn = false;
- }
- if (players.Length < 1)
- canSpawn = false;
- if (spawnedAnimal != null)
- canSpawn = false;
- if (canSpawn)
- SpawnAnimal();
- }
- void SpawnAnimal()
- {
- int arraySum = 0;
- int animalToSpawn = -1;
- System.Random rand = new System.Random();
- int randInt = rand.Next(0, 100);
- for(int i = 0; i < spawnableAnimals.Length; i++)
- {
- if(randInt <= spawnableAnimals[i].spawnChance && randInt > arraySum)
- {
- animalToSpawn = i;
- } else
- {
- arraySum += randInt;
- }
- }
- Debug.Log("Spawning animal: " + animalToSpawn);
- spawnedAnimal = GameObject.Find("AnimalManager").GetComponent<AnimalManager>().SpawnAnimal(spawnableAnimals[animalToSpawn].AnimalName, this.transform.position, this.transform.rotation);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement