Unity 中的着色器可以用三种不同的方式编写:
如果着色器需要受到光照和阴影的影响,则表面着色器是您的最佳选择。表面着色器以简洁的方式使编写复杂的着色器变得容易 - 这是与 Unity 光照管线进行交互的更高级别抽象。大多数表面着色器自动支持前向和延迟光照。您可以用几行 Cg/HLSL 编写表面着色器,随后就能在此基础上自动生成更多代码。
如果您的着色器与光照没有任何关联,请不要使用表面着色器。对于后期处理效果或许多特殊效果着色器,表面着色器是次优选项,因为它们会无缘无故进行大量光照计算。
如果您的着色器不需要与光照交互,或者如果您需要无法由表面着色器处理的非常奇特的效果,则需要使用顶点和片元着色器。以这种方式编写的着色器程序是创建所需效果的最灵活方法(甚至表面着色器也会自动转换为一堆顶点和片元着色器),但这需要付出代价:必须编写更多的代码并且更难以让它与光照互动。这些着色器也是以 Cg/HLSL 编写。
固定函数着色器是传统的着色器语法,用于非常简单的效果。建议编写可编程的着色器,因为这样可以提供更大的灵活性。固定函数着色器完全用一种名为 ShaderLab 的语言编写,此语言类似于 Microsoft 的 .FX 文件或 NVIDIA 的 CgFX。在内部,所有固定函数着色器在导入着色器时转换为顶点和片元着色器。
无论您选择哪种类型的着色器,实际的着色器代码始终包含在用于组织着色器结构的 ShaderLab 中。如下所示:
Shader "MyShader" {
Properties {
_MyTexture ("My Texture", 2D) = "white" { }
// 此处还放置颜色或矢量等其他属性
}
SubShader {
// 此处放置
// - 表面着色器或
// - 顶点和片元着色器或
// - 固定函数着色器
}
SubShader {
// 此处放置上述 SubShader 更简单的 "fallback" 版本
// 此版本能够在较旧的显卡上运行
}
}
我们建议您首先阅读 ShaderLab 参考中的 ShaderLab 语法的一些基本概念,然后继续学习下面列出的教程。
这些教程包含了大量不同类型着色器的示例。Unity 的后期处理效果允许您使用着色器创建许多有趣的效果。
请继续阅读着色器的介绍,并查看着色器参考!
Did you find this page useful? Please give it a rating:
Thanks for rating this page!
What kind of problem would you like to report?
Thanks for letting us know! This page has been marked for review based on your feedback.
If you have time, you can provide more information to help us fix the problem faster.
Provide more information
You've told us this page needs code samples. If you'd like to help us further, you could provide a code sample, or tell us about what kind of code sample you'd like to see:
You've told us there are code samples on this page which don't work. If you know how to fix it, or have something better we could use instead, please let us know:
You've told us there is information missing from this page. Please tell us more about what's missing:
You've told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:
You've told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:
You've told us there is a spelling or grammar error on this page. Please tell us what's wrong:
You've told us this page has a problem. Please tell us more about what's wrong:
Thank you for helping to make the Unity documentation better!
Your feedback has been submitted as a ticket for our documentation team to review.
We are not able to reply to every ticket submitted.