Skip to content

Instantly share code, notes, and snippets.

@Miouyouyou
Last active March 9, 2021 05:02
Show Gist options
  • Save Miouyouyou/09f16fd9fd04414ae5190fd5687985a1 to your computer and use it in GitHub Desktop.
Save Miouyouyou/09f16fd9fd04414ae5190fd5687985a1 to your computer and use it in GitHub Desktop.
Automatically associate textures to materials with the same name on Unity. Put this file inside your Assets folder and a new 'Window -> Custom MeowMeow' window should appear. Select the component with a 'MeshRenderer' to apply it to and click 'apply'.
using UnityEngine;
using System.Collections;
using UnityEditor;
public class TestEditor : EditorWindow
{
public GameObject go;
public Texture[] textures;
[MenuItem("Window / Custom MeowMeow")]
public static void ShowWindow()
{
EditorWindow.GetWindow(typeof(TestEditor));
}
private void OnEnable()
{
/* LoadAll use relative folder paths starting from :
* Assets/Resources
* If you don't have a 'Resources' folder inside Assets,
* create one.
* I haven't tried '../' in the relative path to circumvent
* the need of having a 'Resources' folder.
*/
string textures_relative_dirpath = "MyBeautifulTextures";
textures = Resources.LoadAll<Texture>(textures_relative_dirpath);
Debug.Log("Blah blah");
}
private void OnGUI()
{
/* Fugyly but works. Still, you might want to improve that part
* since it's executed on each GUI frame when the window is
* focused.
*/
ScriptableObject scriptableObj = this;
SerializedObject serialObj = new SerializedObject(scriptableObj);
SerializedProperty serialProp = serialObj.FindProperty("go");
EditorGUILayout.PropertyField(serialProp, true);
serialObj.ApplyModifiedProperties();
/*foreach (Texture tex in textures)
Debug.Log(tex.name);*/
if (GUILayout.Button("Apply"))
{
if (go != null)
{
/* It might be possible to just use Renderer, in order to match
* MeshRenderers AND SkinnedMeshRenderers.
* Meanwhile, you might want to replace MeshRenderer by
* SkinnedMeshRenderer if you want to use this with 3D characters
*/
MeshRenderer mesh_renderer = go.GetComponent<MeshRenderer>();
foreach (Material mat in mesh_renderer.sharedMaterials)
{
//Debug.Log(mat.name);
foreach (Texture tex in textures)
{
if (mat.name == tex.name)
{
mat.SetTexture("_MainTex", tex);
break;
}
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment