图集Sprite作为材质贴图显示
效果
使用的图集
测试shader
注意:如果Sprite带有透明度,注意使用Blend,否则透明部分将显示为黑色
Shader "My/SpriteToMatTex" { Properties { _MainTex ("Texture", 2D) = "white" {} } SubShader { Tags { "Queue" = "Transparent" "RenderType" = "Transparent" } Blend SrcAlpha OneMinusSrcAlpha Pass { CGPROGRAM #pragma vertex vert #pragma fragment frag #include "UnityCG.cginc" struct appdata { float4 vertex : POSITION; float2 uv : TEXCOORD0; }; struct v2f { float4 vertex : SV_POSITION; float2 uv : TEXCOORD0; }; sampler2D _MainTex; float4 _MainTex_ST; v2f vert (appdata v) { v2f o; o.vertex = UnityObjectToClipPos(v.vertex); //模型空间转换为裁剪空间 o.uv = TRANSFORM_TEX(v.uv, _MainTex); //应用tiling, offset return o; } fixed4 frag (v2f i) : SV_Target { fixed4 c = tex2D(_MainTex, i.uv); //像素颜色 return c; } ENDCG } } }
测试代码
using UnityEngine; public class SpriteToMatTexTest : MonoBehaviour { public Sprite m_sprite; public Renderer m_renderer; private MaterialPropertyBlock m_tempMPB; void Start() { m_tempMPB = new MaterialPropertyBlock(); m_renderer.GetPropertyBlock(m_tempMPB); m_tempMPB.SetTexture("_MainTex", m_sprite.texture); var texRect = m_sprite.textureRect; var tex = m_sprite.texture; var texWidth = tex.width; var texHeight = tex.height; var mainTexST = new Vector4( texRect.width / texWidth, texRect.height / texHeight, //tiling texRect.x / texWidth, texRect.y / texHeight //offset ); m_tempMPB.SetVector("_MainTex_ST", mainTexST); m_renderer.SetPropertyBlock(m_tempMPB); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~