Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikibooksThe Free Textbook Project
Search

Cg Programming/Unity/Minimal Shader

From Wikibooks, open books for an open world
<Cg Programming |Unity

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

Starting Unity and Creating a New Project

[edit |edit source]

After downloading and starting Unity, you should create a new project. Choose the "3D" option, i.e., "an empty 3D project that uses Unity's built-in renderer." For this tutorial, you don't need to import any packages.

If you are not familiar with Unity's Scene View, Hierarchy Window, Project Window and Inspector Window, now would be a good time to read the first three sections of theUnity Manual (Unity Basics,Asset Workflow andThe Main Windows).

Creating a Shader

[edit |edit source]

Creating a Cg shader is not complicated: In theProject Window, click on the "+" button (orCreate in the context menu) and chooseShader > Standard Surface Shader. A new file named “NewSurfaceShader” should appear in the Project Window. Double-click it to open it (or right-click and chooseOpen). A text editor with the default shader in Cg should appear. (To change the text editor that is used by Unity chooseEdit > Preferences ... > External Tools from the main menu and change the setting of theExternal Script Editor.)

Now, delete all the text and copy & paste the following shader into this file:

Shader"Cg basic shader"{// defines the name of the shaderSubShader{// Unity chooses the subshader that fits the GPU bestPass{// some shaders require multiple passesCGPROGRAM// 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 shaderfloat4vert(float4vertexPos:POSITION):SV_POSITION// vertex shader{returnUnityObjectToClipPos(vertexPos);// this line transforms the vertex input parameter// and returns it as a nameless vertex output parameter// (with semantic SV_POSITION)}float4frag(void):COLOR// fragment shader{returnfloat4(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 choosingFile > 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 Window 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.

Creating a Material and Attaching a Shader

[edit |edit source]

To create a material, go back to Unity and create a new material by clicking the "+" button in theProject Window (orCreate in the context menu) and choosingMaterial (not(!) "Physics Material"). A new material (by default called “New Material”) should appear in the Project Window. (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 Window. In order to set the shader to this material, you can either

  • drag & drop the shader in theProject Window over the material or
  • select the material in theProject Window and then in theInspector Window choose the shader (in this case “Cg basic shader” as specified in the shader code above) from the drop-down list labeledShader.

In either case, the preview in the Inspector Window of the material should now show a red sphere; if it doesn't, you might have to click on the grey bar at the bottom of the Inspector Window to make it appear. If there is no preview or the sphere is bright magenta, an error message should be displayed at the bottom of the Unity window. In this case, you should reopen the shader and check in the editor whether the text is the same as given above.

Interactively Editing Shaders

[edit |edit source]

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:

float4frag(void):COLOR// fragment shader{returnfloat4(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 Window, the sphere in the Inspector Window 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 andanother about dark blue that is almost black.)

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

float4vert(float4vertexPos:POSITION):SV_POSITION// vertex shader{returnUnityObjectToClipPos(float4(1.0,0.1,1.0,1.0)*vertexPos);}

This flattens any input geometry by multiplying they{\displaystyle y} coordinate with0.1{\displaystyle 0.1}. (This is a component-wise vector product; for more information on vectors and matrices in Cg see the discussion inSection “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 theProject Window and read the messages in theInspector Window, which also include line numbers. You could also open the Console Window by choosingWindow > General > Console from the menu, but this will sometimes not display all error messages and therefore the crucial error is sometimes not reported.

Attaching a Material to a Game Object

[edit |edit source]

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 choosingGameObject > 3D Object > Sphere from the menu. A sphere should appear in the Scene View and the label “Sphere” should appear in the Hierarchy Window. (If it doesn't appear in the Scene View, click it in the Hierarchy Window, 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 theProject Window over the sphere in theHierarchy Window or
  • drag & drop the material from theProject Window over the sphere in theScene View or
  • select the sphere in theHierarchy Window, locate theMesh Renderer component in theInspector Window (and open it by clicking the title if it isn't open), open theMaterials setting of the Mesh Renderer by clicking it. Change the “Default-Material” 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 Window of the material. Changing the shader should (after saving and switching to Unity) change the appearance of the sphere in the Scene View.

Saving Your Work in a Scene

[edit |edit source]

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

One More Note about Terminology

[edit |edit source]

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.

Summary

[edit |edit source]

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.
  • How to create a material and attach a shader to the material.
  • How to manipulate the fragment output parameter with the semanticCOLOR in the fragment shader.
  • How to transform the vertex input parameter with the semanticPOSITION in the vertex shader.
  • How to create a game object and attach a material to it.

Actually, this was quite a lot of stuff.

Further reading

[edit |edit source]

If you still want to know more

<Cg Programming/Unity

Unless stated otherwise, all example source code on this page is granted to the public domain.
Retrieved from "https://en.wikibooks.org/w/index.php?title=Cg_Programming/Unity/Minimal_Shader&oldid=3843484"
Category:

[8]ページ先頭

©2009-2025 Movatter.jp