While I can see ExecuteInEditMode being a useful feature I was wondering if there are potential problems. As I understand it the Update function in the script will still execute if the program is in Play mode. Could this be a potential problem if you want different behaviours in Edit and play mode? For example I may want the blocks to snap to a grid when being placed in the Unity Editor but to be able to move freely when the scene is running. Thinking about this I looked for possible solutions. The one that I found was to use the Application.isPlaying flag to determine whether or not to use the Edit Mode. Thus the EditorSnap C# programt would become:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class EditorSnap : MonoBehaviour {
[SerializeField][Range(1f, 20f)] float gridSize = 10f;
void Update()
{
if (!Application.isPlaying)
{
Vector3 snapPos;
snapPos.x = Mathf.RoundToInt(transform.position.x / gridSize) * gridSize;
snapPos.z = Mathf.RoundToInt(transform.position.z / gridSize) * gridSize;
transform.position = new Vector3(snapPos.x, 0f, snapPos.z);
}
}
}
This may not be relevant to this particular application but might be potentially useful, and it is worth bearing in mind that ExecuteInEditMode may have unexpected consequences. If anyone knows of a better way of handling this please feel free to post.