Skip to content

ThirteeNov

My personal blog about coding and internet

Menu
  • About me
  • About Zofia Kreasi
  • Cart
  • Checkout
  • Making an airplane game from scratch in Unity
  • My account
  • Privacy Policy
  • Privacy Policy – zkLeaderboard
  • Sample Page
  • Shop
  • Tutorials on Learning JavaScript
  • ZKAccounts – Privacy Policy
Menu

Unity Random Spawn Grid : Free script to randomly spawn objects in grid formation

Posted on April 16, 2021April 16, 2021 by Habibie

If you want to spawn your prefab based on an imaginary grid, you can use this script. For example you want to create a scene with a lot of asteroids across the player, you can make an empty game object, attach this script and set reference to your asteroid stone prefab, then run the game.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RandomSpawnGrid : MonoBehaviour
{
	
	public GameObject prefabToSpawn;
	
	public int width = 1000;
	public int length = 1000;
	public int height = 1000;
	public int step = 100;
	public int randomFactor = 3;
	
    // Start is called before the first frame update
    void Start()
    {
		for(int h = 0; h < length/step; h++){
			for(int i = 0; i < width/step; i++){
				int canSpawn = Random.Range(0, randomFactor);
				if(canSpawn == 0){
					Instantiate(prefabToSpawn, new Vector3(((i * step) + transform.position.x) - (width/2), transform.position.y + (Random.Range(-(height/2), (height/2))), ((h * step) + transform.position.z) - (length/2)), Quaternion.Euler(new Vector3( Random.Range(0, 360), Random.Range(0, 360),  Random.Range(0, 360))));
				}
			}
		}
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
Post Views: 326
ciihuy2020

Welcome!

  • My YouTube Channel
  • My GitHub Page
  • About me

Categories

  • 3DVista
  • Android
  • Apache
  • C#
  • Cordova
  • Electron & Node JS
  • HTML5, CSS & JavaScript
  • iOS
  • Let's Make Unity Games
  • Misc
  • Photoshop
  • PHP
  • Python
  • Uncategorized
  • Unity
  • WordPress

Recent Posts

  • Make objects like wires and cables easily in Unity using Ciihuy Curved Mesh
  • [SOLVED] Can’t Add Custom Domain to Blogger After Losing CNAME Verification
  • iOS App Icon Generator by CiihuyCom
  • Advanced Blinking Marker Script to show objects position in your game canvas
  • Ciihuy Images Merger – Fast & Easy Online Image Combiner
© 2025 ThirteeNov | Powered by Superbs Personal Blog theme