using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;

public class MaterialEditor {

    // 使い方
    [MenuItem("MyTools/Rename Material")]
    static void RenameMat()
    {
        Object [] objs = Selection.objects;

        foreach (var obj in objs)
        {
            Material mat = obj as Material;
            if ( mat != null )
            {
                Debug.Log("mat:" + mat.mainTexture.name);
                string path = AssetDatabase.GetAssetPath(obj);
                AssetDatabase.RenameAsset(path, mat.mainTexture.name);
            }
        }
    }

   // 使い方
    [MenuItem("MyTools/Rename GameObject")]
    static void RenameGO()
    {
        GameObject[] objs = Selection.gameObjects;

        foreach (var obj in objs)
        {
            Material mat = obj.GetComponent<Renderer>().sharedMaterial;
            obj.name = mat.name;
        }
    }
 
 
    [MenuItem("MyTools/Assign Material")]
    static void AssignMat()
    {
        Object [] objs = Selection.objects;

        foreach (var obj in objs)
        {
            Material mat = obj as Material;
            if ( mat != null )
            {
                string orgName = mat.name;
                GameObject go = GameObject.Find(orgName) as GameObject;
                if ( go != null )
                {
                    string path = AssetDatabase.GetAssetPath(obj);
                    string dir = Path.GetDirectoryName(path);
                    Debug.Log(dir);
                    string newMatPath = dir + "/" + mat.mainTexture.name + ".mat";
                    Debug.Log(newMatPath);
                    Material anotherMat = AssetDatabase.LoadAssetAtPath<Material>(newMatPath);
                    Debug.Log(anotherMat.name);
                    go.GetComponent<Renderer>().sharedMaterial = anotherMat;
                }
            }
        }
    }

    [MenuItem("MyTools/Assign Specular")]
    static void AssignSpec()
    {
        Object [] objs = Selection.objects;

        foreach (var obj in objs)
        {
            Material mat = obj as Material;
            if ( mat != null )
            {
                string path = AssetDatabase.GetAssetPath(obj);
                string dir = Path.GetDirectoryName(path);
                string specTexPath = dir + "/SpecTextures/" + mat.mainTexture.name + "_s.psd";
                Debug.Log(specTexPath);
                Texture2D specTex = AssetDatabase.LoadAssetAtPath<Texture2D>(specTexPath);
                if (specTex)
                {
                    Debug.Log(specTex.name);
                    mat.SetTexture("_SpecGlossMap", specTex);
                }
            }
        }
    }

}