Place Random Objects on Terrain

Updated on August 3, 2018 in  [R] Scripts
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
42 on August 14, 2014

Hello Everybody!

Here is a simple C# script to place objects with a random position on the terrain.
For example you can place random trees or items on the terrain. 

Script:

 using UnityEngine;
 using System.Collections;
 public class RandomObjects : MonoBehaviour
 {
 public Terrain terrain;
 public int numberOfObjects; // number of objects to place
 private int currentObjects; // number of placed objects
 public GameObject objectToPlace; // GameObject to place
 private int terrainWidth; // terrain size (x)
 private int terrainLength; // terrain size (z)
 private int terrainPosX; // terrain position x
 private int terrainPosZ; // terrain position z
 void Start()
 {
 // terrain size x
 terrainWidth = (int)terrain.terrainData.size.x;
 // terrain size z
 terrainLength = (int)terrain.terrainData.size.z;
 // terrain x position
 terrainPosX = (int)terrain.transform.position.x;
 // terrain z position
 terrainPosZ = (int)terrain.transform.position.z;
 }
 // Update is called once per frame
 void Update()
 {
 // generate objects
 if(currentObjects <= numberOfObjects)
 {
 // generate random x position
 int posx = Random.Range(terrainPosX, terrainPosX + terrainWidth);
 // generate random z position
 int posz = Random.Range(terrainPosZ, terrainPosZ + terrainLength);
 // get the terrain height at the random position
 float posy = Terrain.activeTerrain.SampleHeight(new Vector3(posx, 0, posz));
 // create new gameObject on random position
 GameObject newObject = (GameObject)Instantiate(objectToPlace, new Vector3(posx, posy, posz), Quaternion.identity);
 currentObjects += 1;
 }
 if(currentObjects == numberOfObjects)
 {
 Debug.Log("Generate objects complete!");
 }
 }
 }
 
  • Liked by
  • James Ball
  • Spangui
Reply
1 on August 14, 2014

Hi Fabi, Welcome to the forum. 🙂
Thanks for sharing this with the community. ^^ 😀

Wise
on August 14, 2014

Thanks Spang 🙂

Show more replies
  • Liked by
Reply
Cancel
2 on August 22, 2014

Can i choose weapons and they spawn randomly across the map?

on August 22, 2014

hey can you please answer my question?

Wise
on August 22, 2014

Sorry samurai1789 Yes you can place weapons randomly on the map, but the script is only for one gameobject. 

Show more replies
  • Liked by
Reply
Cancel
3 on August 22, 2014

Hey cool script. I’m just wondering, would this work for a 2D game, say i have alot of platforms spread out on different y coordinates, and i want items to spawn on the platforms, does this script detect colliders and different y and x positions? i know it might sound a bit advanced bust just wanna know 😛

Wise
on August 22, 2014

Thanks JalapenosBud 🙂 The script is not for 2D games. Are the platforms randomly? For example if the platforms are in an array you can generate a random number to find a platform and place there a item. Can you give me more information about the platforms?

on August 22, 2014

Ah okay 🙂 well i just place them randomly by hand, they’re not generated in any way, but is it possible to make a script that detects gameobjects by name and then instantiates another object at a fixed position?

Wise
on August 22, 2014

You can use tags to find gameobjects. 
http://docs.unity3d.com/Manual/Tags.html
http://docs.unity3d.com/ScriptReference/GameObject.FindGameObjectsWithTag.html

You can also find a gameobject with this code:

GameObject.Find("NameOfTheObject");

You can use this to create a new object and set the position:
http://docs.unity3d.com/ScriptReference/Object.Instantiate.html

Show more replies
  • Liked by
Reply
Cancel
1 on August 25, 2014

Good shit man!

Wise
on August 26, 2014

Thanks 🙂

Show more replies
  • Liked by
Reply
Cancel
2 on August 26, 2014

great stuff !

Wise
on August 26, 2014

Thanks 🙂

Wise
on September 8, 2014
Show more replies
  • Liked by
Reply
Cancel
0 on September 8, 2014
using UnityEngine;
using System.Collections;
public class SpawnObjects : MonoBehaviour 
{
public Terrain terrain; // add current terrain
public GameObject objectToPlace; // this object will be placed on terrain
public int numberOfObjects; // number of how many objects will be created
public int posMin; // minimum y position
public int posMax; // maximum x position
public bool posMaxIsTerrainHeight; // the maximum height is the terrain height
private int numberOfPlacedObjects; // number of the plaed objects
private int terrainWidth; // terrain size x axis
private int terrainLength; // terrain size z axis
private int terrainPosX; // terrain position x axis
private int terrainPosZ; // terrain position z axis
// Use this for initialization
void Start () 
{
terrainWidth = (int)terrain.terrainData.size.x; // get terrain size x
terrainLength = (int)terrain.terrainData.size.z; // get terrain size z
terrainPosX = (int)terrain.transform.position.x; // get terrain position x
terrainPosZ = (int)terrain.transform.position.z; // get terrain position z
if(posMaxIsTerrainHeight == true)
{
posMax = (int)terrain.terrainData.size.y;
}
}
// Update is called once per frame
void Update () 
{
// numberOfPlacedObjects is smaller than numberOfObjects
if(numberOfPlacedObjects < numberOfObjects)
{
PlaceObject(); // call function placeObject
}
if(numberOfObjects == numberOfObjects)
{
print("Creating objects complete!");
}
}
// Create objects on the terrain with random positions
void PlaceObject()
{
int posx = Random.Range(terrainPosX, terrainPosX + terrainWidth); // generate random x position
int posz = Random.Range(terrainPosZ, terrainPosZ + terrainLength); // generate random z position
float posy = Terrain.activeTerrain.SampleHeight(new Vector3(posx, 0, posz)); // get the terrain height at the random position
if(posy < posMax && posy > posMin)
{
GameObject newObject = (GameObject)Instantiate(objectToPlace, new Vector3(posx, posy, posz), Quaternion.identity); // create object
numberOfPlacedObjects++;
}
else
{
PlaceObject();
}
}
}

Here is a new version of the script. Now you can set the minimum and maximum of the y coordinates. For example if  you create an island you can set the minimum of the y axis so the objects are not in the water.

  • Liked by
Reply
Cancel
1 on September 13, 2014

That’s awesome man! It would probably be a good idea to hook that up to some kind of object pooling system 🙂 Check this out

Wise
on September 13, 2014

Thanks Brackeys! 🙂 I will look at this.

Show more replies
  • Liked by
Reply
Cancel
14 on November 5, 2014

How do i use it? 

I want to place random platforms.

Wise
on November 5, 2014

First, its only for 3D games. For example place it on an empty gameobject and add the current terrain to the terrain variable, the gameobject you want to place to the objectToPlace variable, the number of the objects you want to place to the numberOfObjects variable and the minimum terrain position and the maximum terrain position to posMin and posMax

on November 5, 2014

It gives me the error: The referenced script on this Behaviour is missing! & Assets/PlatformManager.cs(37,12): warning CS0219: The variable `newObject’ is assigned but its value is never used

What to do?
And, its a 3D game
and i know i am a Noob….

Wise
on November 5, 2014

Do you add your script name for “SpawnObjects” in this line? “public class SpawnObjects : MonoBehaviour"

on November 5, 2014

ok, that error is fixed! Thnx. 
but i get a new error:
Assets/PlatformManager.cs(37,12): warning CS0219: The variable `newObject’ is assigned but its value is never used

Guru
on November 5, 2014

That’s not an error… That’s a warning. For the sake of simplicity, you can just ignore it.

Wise
on November 5, 2014

I get the warning too. At the moment i dont know how to fix this but if i find a way i will tell you.

Guru
on November 5, 2014

At line 49

GameObject newObject = (GameObject)Instantiate(objectToPlace, new Vector3(posx, posy, posz), Quaternion.identity); // create object

The object “newObject” is never used. You can just remove it, which is better for memory too.

Instantiate(objectToPlace, new Vector3(posx, posy, posz), Quaternion.identity); // create object

*sigh, why don’t the code tags work properly now…?*

Wise
on November 5, 2014

Okay thanks Dion Dokter 🙂

on November 5, 2014

It says now: NullReferenceException: Object reference not set to an instance of an object
SpawnObjects.Start () (at Assets/SpawnObjects.cs:16)

Guru
on November 5, 2014

Do you have a terrain in your scene and have it assigned to the script?

Show more replies
  • Liked by
Reply
Cancel
1 on January 18, 2015

the GameObject spawn under the terrain, how to fix it ?

Wise
on January 18, 2015

Do you change something at the code? And do you add the Terrain, object to spawn, number of objects,etc. in the insepctor?

Show more replies
  • Liked by
Reply
Cancel
2 on January 18, 2015

I created a small editor extensions for placing objects on the terrain. 
If you added the file to your project, go to “Window” -> “Place Objects”.

You can download it here.

Hope you like it 🙂

Guru
on January 18, 2015

Cool, everybody always underestimates how usefull those editor windows are!

Guru
on January 20, 2015

Nice work Fabi!

Show more replies
  • Liked by
Reply
Cancel