Advertisement
lemansky

Untitled

Mar 9th, 2021 (edited)
822
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.82 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. [AddComponentMenu("Playground/Gameplay/Object Creator Area")]
  5. [RequireComponent(typeof(BoxCollider2D))]
  6. public class ObjectCreatorArea : MonoBehaviour
  7. {
  8.     [Header("Object creation")]
  9.  
  10.     // The object to spawn
  11.     // WARNING: take if from the Project panel, NOT the Scene/Hierarchy!
  12.     public GameObject prefabToSpawn;
  13.     public GameObject prefabToSpawn1;
  14.     public GameObject prefabToSpawn2;
  15.     public GameObject prefabToSpawn3;
  16.  
  17.     [Header("Other options")]
  18.  
  19.     // Configure the spawning pattern
  20.     public float spawnInterval = 1;
  21.  
  22.     private BoxCollider2D boxCollider2D;
  23.  
  24.     void Start ()
  25.     {
  26.         boxCollider2D = GetComponent<BoxCollider2D>();
  27.  
  28.         StartCoroutine(SpawnObject());
  29.     }
  30.    
  31.     // This will spawn an object, and then wait some time, then spawn another...
  32.     IEnumerator SpawnObject ()
  33.     {
  34.         while(true)
  35.         {
  36.             // Create some random numbers
  37.             float randomX = Random.Range (-boxCollider2D.size.x, boxCollider2D.size.x) *.5f;
  38.             float randomY = Random.Range (-boxCollider2D.size.y, boxCollider2D.size.y) *.5f;
  39.  
  40.             // Generate the new object
  41.             float rnd = Random.value * 4f;
  42.             int rndInt = Mathf.FloorToInt(rnd);
  43.             GameObject newObject = null;
  44.             switch (rndInt)
  45.             {
  46.                 case 0: newObject = Instantiate<GameObject>(prefabToSpawn);break;
  47.                 case 1: newObject = Instantiate<GameObject>(prefabToSpawn1);break;
  48.                 case 2: newObject = Instantiate<GameObject>(prefabToSpawn2);break;
  49.                 case 3: newObject = Instantiate<GameObject>(prefabToSpawn3);break;
  50.                 default: break;
  51.             }
  52.             //GameObject newObject = Instantiate<GameObject>(prefabToSpawn);
  53.             newObject.transform.position = new Vector2(randomX + this.transform.position.x, randomY + this.transform.position.y);
  54.  
  55.             // Wait for some time before spawning another object
  56.             yield return new WaitForSeconds(spawnInterval);
  57.         }
  58.     }
  59. }
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement