Unity selects pictures in batches and converts them into materials

Batch select pictures and convert them to materials

  1. Use Selection.GetFiltered to represent the selected object
    • The first parameter means to retrieve only objects of this type.
    • The second parameter, SelectionMode.Assets, means only returning resource objects in the Asset directory.
  2. First check whether there is a material with this name under the current path, and if it exists, no new material will be generated.
  3. Create a material instance.
  4. Create materials as Asset resources.
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

/// <summary> 照片转换为对应的材质 </summary>
public class ImageTransMaterial : MonoBehaviour
{
    
    
    [Header("材质生成地址")]
    public string materialPath;
    
#if UNITY_EDITOR
    [MenuItem("GameObject/Create Materials")]
    public void SetMat()
    {
    
    
        Object[] m_objects = Selection.GetFiltered(typeof(Texture2D), SelectionMode.Assets); //选择到的物体

        foreach (var i in m_objects)
        {
    
    
            Debug.Log(i.name);

            if (AssetDatabase.LoadAssetAtPath( materialPath + i.name + ".mat",
                typeof(Material))) //判断当前材质是否存在
            {
    
    
                continue;
            }
            else
            {
    
    
                Material mat = new Material(Shader.Find("Legacy Shaders/Diffuse")); //实例一个新的材质
                mat.SetTexture("_MainTex", i as Texture2D); //设置材质的贴图
                AssetDatabase.CreateAsset(mat,
                     materialPath + i.name + ".mat"); //创建材质,并设置材质保存的位置 (需要修改储存位置)
            }
        }
    }
#endif
}

insert image description here

Guess you like

Origin blog.csdn.net/SodasZ/article/details/128396350