Advertisement
Guest User

Untitled

a guest
Apr 30th, 2016
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. [System.Serializable]
  2. public class SpawnableAnimal
  3. {
  4. public string AnimalName;
  5. public int spawnChance;
  6. }
  7.  
  8. public class AnimalSpawner : MonoBehaviour {
  9.  
  10. public float maxSpawnRadius = 1000.0f;
  11. public float noSpawnRadius = 700.0f;
  12.  
  13. public GameObject spawnedAnimal;
  14.  
  15. public SpawnableAnimal[] spawnableAnimals;
  16.  
  17. void Start () {
  18. System.Random rand = new System.Random();
  19. int randInt = rand.Next(0, 100);
  20.  
  21. float startTime = randInt / 100;
  22. float repeatTime = randInt / 100;
  23. InvokeRepeating("ReadyToSpawn", startTime, (60.0f + repeatTime));
  24. }
  25.  
  26. void ReadyToSpawn()
  27. {
  28. Debug.Log("Ready to spawn");
  29. bool canSpawn = true;
  30.  
  31. GameObject[] players = GameObject.FindGameObjectsWithTag("Player");
  32. GameObject[] animals = GameObject.FindGameObjectsWithTag("Animal");
  33. for(int i = 0; i < players.Length; i++)
  34. {
  35. if (Vector3.Distance(this.transform.position, players[i].transform.position) > maxSpawnRadius)
  36. canSpawn = false;
  37.  
  38. if (Vector3.Distance(this.transform.position, players[i].transform.position) < noSpawnRadius)
  39. canSpawn = false;
  40. }
  41.  
  42. if (players.Length < 1)
  43. canSpawn = false;
  44.  
  45. if (spawnedAnimal != null)
  46. canSpawn = false;
  47.  
  48. if (canSpawn)
  49. SpawnAnimal();
  50. }
  51.  
  52. void SpawnAnimal()
  53. {
  54. int arraySum = 0;
  55. int animalToSpawn = -1;
  56. System.Random rand = new System.Random();
  57. int randInt = rand.Next(0, 100);
  58.  
  59. for(int i = 0; i < spawnableAnimals.Length; i++)
  60. {
  61. if(randInt <= spawnableAnimals[i].spawnChance && randInt > arraySum)
  62. {
  63. animalToSpawn = i;
  64. } else
  65. {
  66. arraySum += randInt;
  67. }
  68. }
  69.  
  70. Debug.Log("Spawning animal: " + animalToSpawn);
  71. spawnedAnimal = GameObject.Find("AnimalManager").GetComponent<AnimalManager>().SpawnAnimal(spawnableAnimals[animalToSpawn].AnimalName, this.transform.position, this.transform.rotation);
  72. }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement