Unity3d脚本改变GameObject的Material(一)

Unity3d Change Material by Script Test(1)

主要用于修改使用Unity3d内部的材质球 Default-Particle,打包时会冗余多分Default-Particle的Texture2D。打算使用制作的Material替换,再使用依赖打包,实现Texture2D的提取。

using System;
using UnityEditor;
using UnityEngine;

public class ReplaceComponent
{
    private static void Repalce()
    {
        UnityEngine.GameObject[] selections = Selection.gameObjects;

        UnityEngine.Object obj = AssetDatabase.LoadMainAssetAtPath("Assets/test.mat");
        Material mat = obj as Material;

        foreach (var o in selections)
        {
            SetObjRecursively(o,mat);
        }

        AssetDatabase.SaveAssets();
    }

    static void SetObjRecursively(GameObject rootObj,Material mat)
    {
        if (null != rootObj.renderer)
        {
            Debug.Log(rootObj.renderer.name);
        }
        if (null != rootObj.particleSystem)
        {
            Debug.Log(rootObj.particleSystem.name);
            if (null != rootObj.particleSystem.renderer)
            {
                if ("Default-Particle (Instance)" == rootObj.particleSystem.renderer.material.name)
                    rootObj.particleSystem.renderer.material = mat;
            }
        }
        System.Collections.Generic.IEnumerable<GameObject> subObj = rootObj.GetDirectChildren();
        System.Collections.Generic.IEnumerator<GameObject> e = subObj.GetEnumerator();
        if (null != rootObj)
        {
            while (e.MoveNext())
            {
                SetObjRecursively(e.Current,mat);
            }
        }
    }

    [MenuItem("EctypeEditor/Replace Component")]
    static void ReplaceComponentSelect()
    {
        Repalce();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值