Hello!
Recently I’ve been having lots of problems with the Unity’s vertex snapping tool, so I decided to make my own simple tool. I have made everything expect the final thing, which is moving the object to the selected vertex.
Below you can see the full script, the way it works is you drag and drop a target object and a reference object. You select the target vertex and then the reference vertex and the target should snap to the selected reference vertex. Although, I’m not sure how to do that.
It’s not the best script at the moment, but right now I’m just trying to get this to work and then I can improve it a bit more.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class SnappingTool : EditorWindow
{
GameObject target;
GameObject reference;
bool selected;
[MenuItem("Window/Snapping Tool")]
public static void OpenWindow()
{
var window = EditorWindow.GetWindow<SnappingTool>();
window.Show();
}
private void OnEnable()
{
SceneView.duringSceneGui += OnSceneGUI;
}
private void OnDisable()
{
SceneView.duringSceneGui -= OnSceneGUI;
}
private void OnGUI()
{
target = (GameObject)EditorGUILayout.ObjectField(new GUIContent("Target"), target, typeof(GameObject), allowSceneObjects: true);
reference = (GameObject)EditorGUILayout.ObjectField(new GUIContent("Reference"), reference, typeof(GameObject), allowSceneObjects: true);
}
void OnSceneGUI(SceneView sv)
{
if (!target || !reference) { return; }
var tFilter = target.GetComponent<MeshFilter>();
var rFilter = reference.GetComponent<MeshFilter>();
if (!tFilter || !rFilter) { return; }
if (selected)
{
DrawHandles(reference, rFilter.sharedMesh);
}
else
{
DrawHandles(target, tFilter.sharedMesh);
}
}
void DrawHandles(GameObject obj, Mesh mesh)
{
Matrix4x4 localToWorld = obj.transform.localToWorldMatrix;
for (int i = 0; i < mesh.vertices.Length; i++)
{
var pos = localToWorld.MultiplyPoint3x4(mesh.vertices[i]);
Handles.color = Color.red;
bool pressed = Handles.Button(pos, Quaternion.identity, .025f, 0.025f, Handles.SphereHandleCap);
if (pressed && !selected)
{
selected = true;
}
if (pressed && selected)
{
selected = false;
//SNAP.
}
}
}
}