Skip to content

Instantly share code, notes, and snippets.

@Sacristan
Created April 26, 2020 22:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sacristan/eb97fe21795249c0ebded882d8f09c13 to your computer and use it in GitHub Desktop.
Save Sacristan/eb97fe21795249c0ebded882d8f09c13 to your computer and use it in GitHub Desktop.
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
public class PerlinGridPlacer : EditorWindow
{
private const string RootObjectName = "PerlinGridPlacerRESULT";
[MenuItem("Window/Tools/PerlinGridPlacer")]
public static void ShowWindow()
{
EditorWindow.GetWindow(typeof(PerlinGridPlacer));
}
private GameObject prefab;
private Transform origin;
private int cellsX = 50;
private int cellsY = 50;
private float cellStepDist = 5f;
private float perlinScale = 0.15f;
private float perlinTreshold = 0.1f;
void OnGUI()
{
prefab = EditorGUILayout.ObjectField("Prefab:", prefab, typeof(GameObject), false) as GameObject;
origin = EditorGUILayout.ObjectField("Origin:", origin, typeof(Transform), true) as Transform;
cellsX = EditorGUILayout.IntField("CellsX", cellsX);
cellsY = EditorGUILayout.IntField("CellsY", cellsY);
cellStepDist = EditorGUILayout.FloatField("cellStepDist", cellStepDist);
perlinScale = EditorGUILayout.FloatField("PerlinScale", perlinScale);
perlinTreshold = EditorGUILayout.FloatField("PerlinTreshold", perlinTreshold);
if (GUILayout.Button("Place!")) DoMagic();
}
public void DoMagic()
{
Clear();
GameObject root = new GameObject(RootObjectName);
float xOff = cellsX * cellStepDist * 0.5f;
float zOff = cellsY * cellStepDist * 0.5f;
float scaler = Random.value * perlinScale;
for (int x = 0; x < cellsX; x++)
{
for (int z = 0; z < cellsY; z++)
{
if (Mathf.PerlinNoise(x * scaler, z * scaler) < perlinTreshold)
{
Vector3 pos = new Vector3(cellStepDist * x - xOff, 0, cellStepDist * z - zOff);
AddObject(pos, root.transform);
}
}
}
}
private void AddObject(Vector3 offset, Transform parent)
{
GameObject obj = PrefabUtility.InstantiatePrefab(prefab) as GameObject;
obj.transform.position = origin.position + offset;
obj.transform.parent = parent;
}
public void Clear()
{
GameObject root = GameObject.Find(RootObjectName);
if (root) DestroyImmediate(root);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment