Advertisement
Guest User

Untitled

a guest
Apr 7th, 2020
250
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.72 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class Example : MonoBehaviour
  6. {
  7.     public GameObject objectToSpawn; //prefab or gameobject
  8.     public Transform objectContainer; //parent
  9.  
  10.     public float thingsToSpawn = 5f;
  11.  
  12.     public float radius = 5f;
  13.  
  14.     public float min = 0.5f;
  15.     public float max = 1f;
  16.  
  17.     [Header("Press me to spawn things")]
  18.     public bool toSpawn = false; //flipflop flag
  19.  
  20.     int objectID = 0; //arrays start from 0
  21.     string objName;
  22.     string objNameBase = "base";
  23.  
  24.     private GameObject newObject; //Creates a new object.
  25.  
  26.  
  27.     void Update()
  28.     {
  29.         if (toSpawn)
  30.         {
  31.             SpawnObjects();
  32.  
  33.             toSpawn = false;
  34.         }      
  35.     }
  36.  
  37.     public void SpawnObjects() //The function that spawns the objects in the scene.
  38.     {
  39.         for (int i = 0; i < thingsToSpawn; i++)
  40.         {
  41.             Vector2 spawnCircle = Random.insideUnitSphere * radius; //The spawn radius that the object will appear.
  42.             Vector3 spawnPos = new Vector3(spawnCircle.x, 0f, spawnCircle.y); //The spawn position of the object.
  43.             float objectScale = Random.Range(min, max); //Gives a random scale to the object.
  44.  
  45.             newObject = Instantiate(objectToSpawn, spawnPos, Quaternion.Euler(new Vector3(0, Random.Range(0, 360))), objectContainer); //This is where the object is instantiated with a random rotation.
  46.  
  47.             objName = objNameBase + objectID.ToString();
  48.             objectID++;
  49.            
  50.             newObject.name = objName; //This is where the name is applied to the object.
  51.             newObject.transform.localScale = Vector3.one * objectScale; //Sets the scale.
  52.         }
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement