- Home /
Interactively work on a programmatic mesh
Hi! I'm working on code that generates a mesh, like in this example.
using UnityEngine;
using System.Collections;
[ExecuteInEditMode]
public class MeshBehaviour : MonoBehaviour {
void Start() {
gameObject.AddComponent<MeshFilter>();
gameObject.AddComponent<MeshRenderer>();
Mesh mesh = GetComponent<MeshFilter>().mesh;
mesh.Clear();
mesh.vertices = new Vector3[] {new Vector3(0, 0, 0), new Vector3(0, 1, 0), new Vector3(1, 1, 0)};
mesh.uv = new Vector2[] {new Vector2(0, 0), new Vector2(0, 1), new Vector2(1, 1)};
mesh.triangles = new int[] {0, 1, 2};
}
}
What I want in this particular case is to iterate quickly, i.e. not having to exit and enter play mode all the time. So I found this [ExecuteInEditMode]
attribute which enables rendering of the custom mesh in edit mode. Unfortunately when I change the code and save the script (in MonoDevelop) nothing happens. If I enter play mode or exit it, then the changes become active.
Is there a way to reload a script in Unity upon change for both play mode and edit mode?
Answer by Zak_33 · Mar 15, 2016 at 08:46 PM
I think what you want is the DidReloadScripts attribute. Static methods with this attribute will be called every time Unity reloads a script file from your project.
Have a look at this code. It will recreate the mesh whenever you modify the code, without the need to enter/exit play mode.
using UnityEngine;
[ExecuteInEditMode]
public class MeshBehaviour : MonoBehaviour
{
[UnityEditor.Callbacks.DidReloadScripts]
static void CreateMesh()
{
Mesh mesh = FindObjectOfType<MeshBehaviour>().GetComponent<MeshFilter>().sharedMesh;
mesh.Clear();
mesh.vertices = new Vector3[] { new Vector3(0, 0, 0), new Vector3(0, 1, 0), new Vector3(1, 1, 0) };
mesh.uv = new Vector2[] { new Vector2(0, 0), new Vector2(0, 1), new Vector2(1, 1) };
mesh.triangles = new int[] { 0, 1,2 };
}
void Start()
{
if (gameObject.GetComponent<MeshFilter>() == null)
{
gameObject.AddComponent<MeshFilter>();
}
if (gameObject.GetComponent<MeshRenderer>() == null)
{
gameObject.AddComponent<MeshRenderer>();
}
CreateMesh();
}
}
This code only works if you have exactly one instance of your script in the scene, but you can adapt it to handle more.
As a side note, you should comment the DidReloadScripts line once you are done working on your mesh, as it will keep recreating it even if you modify only another script.