Skip to content

Instantly share code, notes, and snippets.

@staggartcreations
Created February 27, 2025 08:53
Show Gist options
  • Save staggartcreations/9756530d4521b46be14eb3acbcd3b707 to your computer and use it in GitHub Desktop.
Save staggartcreations/9756530d4521b46be14eb3acbcd3b707 to your computer and use it in GitHub Desktop.
Terrain layer color editor
//Copy-paste me in a script file named "TerrainColorImporter" and place it in any folder called "Editor"
using UnityEngine;
using UnityEditor;
using UnityEditor.AssetImporters;
using System.IO;
[ScriptedImporter(1, FILE_EXTENSION)]
public class TerrainColorImporter : ScriptedImporter
{
private const string FILE_EXTENSION = "terraincolor";
public Color color = Color.white;
[Range(0f,1f)]
public float smoothness = 0.15f;
private const int textureSize = 4;
private Texture2D _icon;
private Texture2D icon
{
get
{
if(_icon == null) _icon = EditorGUIUtility.IconContent("PreTextureRGB").image as Texture2D;
return _icon;
}
}
public override void OnImportAsset(AssetImportContext ctx)
{
Texture2D texture = new Texture2D(textureSize, textureSize, TextureFormat.RGBA32, true);
Color[] pixels = new Color[textureSize * textureSize];
for (int i = 0; i < pixels.Length; i++)
{
pixels[i] = color;
pixels[i].a = smoothness;
}
texture.SetPixels(pixels);
texture.name = this.name + " Color";
texture.Apply();
TerrainLayer terrainLayer = new TerrainLayer
{
diffuseTexture = texture,
tileSize = Vector2.one,
name = this.name + "_Layer",
smoothness = smoothness,
};
ctx.AddObjectToAsset("TerrainLayer", terrainLayer, icon);
ctx.AddObjectToAsset("MainTexture", texture);
ctx.SetMainObject(terrainLayer);
}
[MenuItem("Assets/Create/Terrain/Color Layer", false, 2000)]
public static void CreateColorTextureFile()
{
ProjectWindowUtil.CreateAssetWithContent($"New Terrain Color.{FILE_EXTENSION}", "");
}
//Handles correct behaviour when double-clicking a .watermesh asset assigned to a field
//Otherwise the OS prompts to open it
[UnityEditor.Callbacks.OnOpenAsset]
public static bool OnOpenAsset(int instanceID, int line)
{
Object target = EditorUtility.InstanceIDToObject(instanceID);
if (target is Mesh)
{
var path = AssetDatabase.GetAssetPath(instanceID);
if (Path.GetExtension(path) != "." + FILE_EXTENSION) return false;
Selection.activeObject = target;
return true;
}
return false;
}
}
[CustomEditor(typeof(TerrainColorImporter))]
public class TerrainColorImporterEditor : ScriptedImporterEditor
{
public override void OnInspectorGUI()
{
EditorGUI.BeginChangeCheck();
base.OnInspectorGUI();
if (EditorGUI.EndChangeCheck() && HasModified())
{
#if UNITY_2022_2_OR_NEWER
this.SaveChanges();
#else
this.ApplyAndImport();
#endif
}
EditorGUILayout.Space();
//EditorGUILayout.LabelField("- Staggart Creations -", EditorStyles.centeredGreyMiniLabel);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment