Unity 材质系统优化(mesh相同,图片不同,但是可以将所有的图片合成一张图集)

今天提供一个Unity材质优化的思路,流程是这样的,模型的mesh相同只是图片不同,我想着能不能将所有的图片合成一张图集呢,于是我就试着在Blender里面开搞了,所有的mesh相同的模型,共用一个材质(图集相同),

一:前期准备 TP图片打包,Blender UV展开

利用TP将所有的图片打包出一个图片 我这里使用TexturePacker打包的,导入到Blender里面,效果如下:

对模型展开UV,将UV进行缩放,缩放到合适位置,下一步就是导出模型文件,在Unity C#脚本里面进行UV坐标的偏移了,这样做的目的就是保证所有的球都用的是 同一个mesh,同一个材质,达到优化的目的

二: Unity C#脚本编写

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// URP 现代管线中 每增加一个台球会增加4个drawcall
/// 通用管线中,每增加一个台球会增加2个drawcall
/// </summary>
public class Ball : MonoBehaviour
{
    [SerializeField]
    private Material ballMaterial;
    private List<Vector2> offsetList = new();

    public int ballNumber = 1;

    public int BallNumber {
        get {
            return ballNumber;
        }
        private set {
            ballNumber = value;
        }

    }
    // Start is called before the first frame update
    void Start()
    {
        InitAllOffset();
        InitMat();
    }

    private void InitAllOffset() {
        offsetList.Add(new Vector2(0,0));
        offsetList.Add(new Vector2(0.33f,0));
        offsetList.Add(new Vector2(0.67f,0));

        offsetList.Add(new Vector2(0,-0.2f));
        offsetList.Add(new Vector2(0.34f,-0.2f));
        offsetList.Add(new Vector2(0.67f,-0.2f));

        offsetList.Add(new Vector2(0,-0.4f));
        offsetList.Add(new Vector2(0.33f,-0.4f));
        offsetList.Add(new Vector2(0.67f,-0.4f));

        offsetList.Add(new Vector2(0f,-0.6f));
        offsetList.Add(new Vector2(0.34f,-0.6f));
        offsetList.Add(new Vector2(0.67f,-0.6f));

        offsetList.Add(new Vector2(0f,-0.8f));
        offsetList.Add(new Vector2(0.33f,-0.8f));
        offsetList.Add(new Vector2(0.67f,-0.8f));
    }

    private void InitMat() {
        Vector2 targetUvOffset = offsetList[BallNumber - 1];

        // mat.SetTextureOffset("_BaseMap",targetUvOffset);
        // mat.SetVector("Offset",);
        Renderer render = GetComponent<Renderer>();
        if(render != null) {
            Debug.Log("重新设置材质");
            render.material.SetTextureOffset("_MainTex",targetUvOffset);
        }
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

  • 8
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值