Files
obsidian-notes/3Resources/游戏开发/性能优化/卡片/Texture、Texture2D与RenderTexture.md
2025-10-09 20:47:44 +08:00

68 lines
2.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
tags:
- Texture
- Texture2D
- RenderTexture
---
### Texture Texture2D RenderTexture
三者关系与差别如下:
---
### 一、继承与本质关系
|类型|基类|存储位置|用途|
|---|---|---|---|
|**Texture**|基类|GPU|所有纹理的抽象基类|
|**Texture2D**|派生自 Texture|GPU|常规 2D 纹理,可读写像素|
|**RenderTexture**|派生自 Texture|GPU|可作为渲染目标的纹理|
---
### 二、功能差异
| 特性 | Texture2D | RenderTexture |
| -------------------- | --------------------------------------- | -------------------------------------------- |
| 是否可被采样(用于材质) | ✔ | ✔ |
| 是否可写入CPU端 | ✔(`SetPixels`/`LoadRawTextureData` | ✖仅GPU写 |
| 是否可作为渲染目标 | ✖ | ✔Camera/Graphics.Blit可直接输出 |
| 是否支持MipMap | ✔ | ✔(可选) |
| 是否可用于ComputeShader读写 | 读可用(`Texture2D` <br>写需`RWTexture2D`绑定 | 读写都可(`RenderTexture.enableRandomWrite=true` |
| 是否可保存为文件 | ✔(`EncodeToPNG`/`ReadPixels` | 需先复制到`Texture2D`再保存 |
---
### 三、常见交互流程
1. **GPU渲染到RenderTexture → 读取像素到Texture2D**
```CSharp
RenderTexture rt = new RenderTexture(512, 512, 0); Camera.main.targetTexture = rt; Camera.main.Render(); Texture2D tex = new Texture2D(512, 512, TextureFormat.RGBA32, false); RenderTexture.active = rt; tex.ReadPixels(new Rect(0, 0, 512, 512), 0, 0); tex.Apply(); RenderTexture.active = null;
```
此流程用于截图或生成贴图资产。
2. **Texture2D 复制内容到 RenderTexture**
`Graphics.Blit(texture2D, renderTexture);`
仅在shader中使用时保留GPU端数据不经CPU拷贝。
3. **RenderTexture 作为材质输入:**
`material.SetTexture("_MainTex", renderTexture);`
---
### 四、性能与使用建议
- `Texture2D` 适合静态资源贴图、UI图标、字体图集
- `RenderTexture` 适合动态生成后期处理、离屏渲染、动态阴影、SDF生成
- CPU访问`RenderTexture`代价高,应尽量避免频繁`ReadPixels`。
- 若仅GPU间数据流转用`RenderTexture`或`ComputeBuffer`,不要回读。