Skip to content

Instantly share code, notes, and snippets.

@romainPechot
Created November 18, 2015 17:14
Show Gist options
  • Save romainPechot/8261d2694791c6d24600 to your computer and use it in GitHub Desktop.
Save romainPechot/8261d2694791c6d24600 to your computer and use it in GitHub Desktop.
Unity Editor Script Replace Mesh
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
public class ReplaceMesh : EditorWindow
{
[MenuItem("Window/Help/Mesh/Replace")]
private static void Init()
{
ReplaceMesh _window = GetWindow<ReplaceMesh>();
_window.titleContent = new GUIContent("Replace Mesh");
_window.Show();
}// Init()
private Mesh _M_from;
private Mesh _M_to;
private Vector3 _V3_offset;
private bool _b_savePrefab = true;
private MeshFilter[] _aMF_instances;
private void OnGUI()
{
// from
_M_from = (Mesh)EditorGUILayout.ObjectField("Find", _M_from, typeof(Mesh), true);
// to
_M_to = (Mesh)EditorGUILayout.ObjectField("Replace with", _M_to, typeof(Mesh), false);
// offset
_V3_offset = EditorGUILayout.Vector3Field("Offset Rotation", _V3_offset);
// save prefab ?
_b_savePrefab = EditorGUILayout.Toggle("Save Prefab", _b_savePrefab);
if(_aMF_instances != null)
{
GUILayout.Label("Find " + _aMF_instances.Length + " instance(s).");
}
if(_M_from != null)
{
if(GUILayout.Button("Find")) FindInstances();
if(_M_to != null)
{
if(GUILayout.Button("Replace"))
{
FindInstances();
ReplaceInstances();
}
}
}
}// OnGUI()
private void FindInstances()
{
_aMF_instances = (MeshFilter[])GameObject.FindObjectsOfType(typeof(MeshFilter));
List<MeshFilter> _LMF = new List<MeshFilter>(_aMF_instances.Length);
for(int i = 0; i < _aMF_instances.Length; i++)
{
if(_aMF_instances[i].sharedMesh == _M_from) _LMF.Add(_aMF_instances[i]);
}//for()
_aMF_instances = _LMF.ToArray();
}// FindInstances()
private void ReplaceInstances()
{
if(!ICollectionHelper.IsNullOrEmpty(_aMF_instances))
{
if(!_b_savePrefab)
{
for(int i = 0; i < _aMF_instances.Length; i++)
{
if(_aMF_instances[i] != null)
{
// set mesh
_aMF_instances[i].sharedMesh = _M_to;
// change rotation
Vector3 _V3_rot = _aMF_instances[i].transform.localRotation.eulerAngles;
_V3_rot += _V3_offset;
_aMF_instances[i].transform.localRotation = Quaternion.Euler(_V3_rot);
}
}//for()
}
else
{
for(int i = 0; i < _aMF_instances.Length; i++)
{
if(_aMF_instances[i] != null)
{
// set mesh
_aMF_instances[i].sharedMesh = _M_to;
// change rotation
Vector3 _V3_rot = _aMF_instances[i].transform.localRotation.eulerAngles;
_V3_rot += _V3_offset;
_aMF_instances[i].transform.localRotation = Quaternion.Euler(_V3_rot);
Object obj = PrefabUtility.GetPrefabParent(_aMF_instances[i].gameObject);
if(obj != null)
{
PrefabUtility.ReplacePrefab(_aMF_instances[i].gameObject, obj, ReplacePrefabOptions.ConnectToPrefab | ReplacePrefabOptions.ReplaceNameBased);
}
}
}//for()
}
}
}// ReplaceInstances()
}// ReplaceMesh
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment