2.1.1 Minimal Shader (about shaders, materials, and game objects) 极简的着色器(关于着色器,材质和游戏物体)

This tutorial covers the basic steps to create a minimal Cg shader in Unity.

这篇教程包含了在Unity中创建一个最简单的Cg着色器的基本步骤。

1.Starting Unity and Creating a New Project

After downloading and starting Unity, you might see an empty project. If not, you should create a new project by choosing File > New Project... from the menu. For this tutorial, you don't need to import any packages but some of the more advanced tutorials require the scripts and skyboxes packages.

If you are not familiar with Unity's Scene View, Hierarchy View, Project View and Inspector View, now would be a good time to read the first two sections of the Unity Manual (“Unity Basics” and“Building Scenes”).

2.Creating a Shader

Creating a Cg shader is not complicated: In the Project View, click on Create and choose Shader. A new file named “NewShader” should appear in the Project View. Double-click it to open it (or right-click and choose Open). An editor with the default shader in Cg should appear. Delete all the text and copy & paste the following shader into this file:

Shader "Cg basic shader" { // defines the name of the shader 
   SubShader { // Unity chooses the subshader that fits the GPU best
      Pass { // some shaders require multiple passes
         CGPROGRAM // here begins the part in Unity's Cg

         #pragma vertex vert 
            // this specifies the vert function as the vertex shader 
         #pragma fragment frag
            // this specifies the frag function as the fragment shader

         float4 vert(float4 vertexPos : POSITION) : SV_POSITION 
            // vertex shader 
         {
            return mul(UNITY_MATRIX_MVP, vertexPos);
               // this line transforms the vertex input parameter 
               // vertexPos with the built-in matrix UNITY_MATRIX_MVP
               // and returns it as a nameless vertex output parameter 
         }

         float4 frag(void) : COLOR // fragment shader
         {
            return float4(1.0, 0.0, 0.0, 1.0); 
               // this fragment shader returns a nameless fragment
               // output parameter (with semantic COLOR) that is set to
               // opaque red (red = 1, green = 0, blue = 0, alpha = 1)
         }

         ENDCG // here ends the part in Cg 
      }
   }
}

Save the shader (by clicking the save icon or choosing File > Save from the editor's menu).

Congratulations, you have just created a shader in Unity. If you want, you can rename the shader file in the Project View by clicking the name, typing a new name, and pressing Return. (After renaming, reopen the shader in the editor to make sure that you are editing the correct file.)

Unfortunately, there isn't anything to see until the shader is attached to a material.

3.Creating a Material and Attaching a Shader

To create a material, go back to Unity and create a new material by clicking Create in the Project View and choosing Material. A new material called “New Material” should appear in the Project View. (You can rename it just like the shader.) If it isn't selected, select it by clicking. Details about the material appear now in the Inspector View. In order to set the shader to this material, you can either

  • drag & drop the shader in the Project View over the material or
  • select the material in the Project View and then in the Inspector View choose the shader (in this case “Cg basic shader” as specified in the shader code above) from the drop-down list labeled Shader.

In either case, the Preview in the Inspector View of the material should now show a red sphere. If it doesn't and an error message is displayed at the bottom of the Unity window, you should reopen the shader and check in the editor whether the text is the same as given above.

4.Interactively Editing Shaders

This would be a good time to play with the shader; in particular, you can easily change the computed fragment color. Try neon green by opening the shader and replacing the fragment shader in thefrag function with this code:

         float4 frag(void) : COLOR // fragment shader
         {
            return float4(0.6, 1.0, 0.0, 1.0); 
               // (red = 0.6, green = 1.0, blue = 0.0, alpha = 1.0)
         }

You have to save the code in the editor and activate the Unity window again to apply the new shader. If you select the material in the Project View, the sphere in the Inspector View should now be green. You could also try to modify the red, green, and blue components to find the warmest orange or the darkest blue. (Actually, there is amovie about finding the warmest orange and another about dark blue that is almost black.)

You could also play with the vertex shader in the functionvert, e.g. try this vertex shader:

         float4 vert(float4 vertexPos : POSITION) : SV_POSITION 
            // vertex shader 
         {
            return mul(UNITY_MATRIX_MVP,float4(1.0, 0.1, 1.0, 1.0) * vertexPos);
         }

This flattens any input geometry by multiplying they coordinate with0.1. (This is a component-wise vector product; for more information on vectors and matrices in Cg see the discussion in Section “Vector and Matrix Operations”.)

In case the shader does not compile, Unity displays an error message at the bottom of the Unity window and displays the material as bright magenta. In order to see all error messages and warnings, you should select the shader in the  Project View and read the messages in the Inspector View, which also include line numbers. You could also open the Console View by choosing Window > Console from the menu, but this will not display all error messages and therefore the crucial error is often not reported.

5.Attaching a Material to a Game Object

We still have one important step to go: attaching the new material to a triangle mesh. To this end, create a sphere (which is one of the predefined game objects of Unity) by choosing GameObject > 3D Object > Sphere from the menu. A sphere should appear in the Scene View and the label “Sphere” should appear in the Hierarchy View. (If it doesn't appear in the Scene View, click it in the Hierarchy View, move (without clicking) the mouse over the Scene View and press “f”. The sphere should now appear centered in the Scene View.)

To attach the material to the new sphere, you can:

  • drag & drop the material from the Project View over the sphere in the Hierarchy View or
  • drag & drop the material from the Project View over the sphere in the Scene View or
  • select the sphere in the Hierarchy View, locate the Mesh Renderer component in the Inspector View (and open it by clicking the title if it isn't open), open the Materials setting of the Mesh Renderer by clicking it. Change the “Default-Diffuse” material to the new material by clicking the dotted circle icon to the right of the “Element 0” slot and choosing the new material from the pop-up window. (Or drag & drop the new material into the “Element 0” slot.)

In any case, the sphere in the Scene View should now have the same color as the preview in the Inspector View of the material. Changing the shader should (after saving and switching to Unity) change the appearance of the sphere in the Scene View.

6.Saving Your Work in a Scene

There is one more thing: you should save you work in a “scene” (which often corresponds to a game level). Choose  File > Save Scene (or File > Save Scene As...) and choose a file name in the “Assets” directory of your project. The scene file should then appear in the Project View and will be available the next time you open the project.

7.One More Note about Terminology

It might be good to clarify the terminology. In some APIs, a “shader” is either a vertex shader or a fragment shader. The combination of both is called a “program”. In other APIs, it's just the other way around: a “program” is either a vertex program or a fragment program, and the combination of both is a “shader”. Unfortunately, Unity's documentation mixes both conventions. To keep things simple, we try to avoid the term “program” here and use the term “shader” to denote the combination of a vertex shader and a fragment shader.

8.Summary

Congratulations, you have reached the end of this tutorial. A few of the things you have seen are:

  • How to create a shader.

    如何创建一个着色器。

  • How to define a Cg vertex and fragment shader in Unity.

    如何在Unity中定义一个Cg顶点和片段着色器。

  • How to create a material and attach a shader to the material.

    如何创建一个材质并把着色器附加到材质上。

  • How to manipulate the fragment ouput parameter with the semantic COLOR in the fragment shader.

    如何在片段着色器中用 COLOR 语义控制片段的输出参数。

  • How to transform the vertex input parameter with the semantic POSITION in the vertex shader.

    如何在顶点着色器中用 POSITION 语义变换顶点输入参数。

  • How to create a game object and attach a material to it.

    如何创建一个游戏对象并赋予它材质。

Actually, this was quite a lot of stuff.

9.Further Reading 延伸阅读

If you still want to know more

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值