A shader is a small program containing instructions for the GPU. They describe how to calculate the onscreen color of a particular material.

Though Unity provides a Standard Shader, sometimes you may need to make an effect beyond what the out-of-the-box shader can do.

Historically, this has required a special shading language, such as Cg or HLSL, with conventions a bit different than typical gameplay scripting. For many, shader writing is a neglected area of game development, simply because of the extra learning curve involved.

Shader Graph in Unity for beginners

Unity introduced Shader Graph to allow you to more easlily write shaders, with minimal to no coding. Best of all, Shader Graph makes it easy to get started with a visual, interactive interface.

In this tutorial, you’re going to create your first shader graph in Unity right now!

Getting Started

This tutorial uses Unity version 2019.1 or newer. You can get your version of Unity here.

Note: While this tutorial is for beginners in Shader Graph, it assumes you know the basics of Unity development and getting around the interface. If you’re new to Unity development, check out this great Getting Started In Unity tutorial.

Use the Download Materials button at the top or bottom of this page to grab the materials for this tutorial. Then unzip its contents and open Intro to Shader Graph Starter inside Unity.

The RW folder in the Project Window is organized as follows:

  • Fonts: Fonts used in the scene.
  • Materials: Materials for the scene.
  • Models: 3D meshes for the game pieces and background.
  • PostFX: Post-processing effects for scene rendering.
  • Prefabs: Various pre-built components.
  • Scenes: The game scene.
  • Scripts: Custom scripted game logic.
  • Shaders: The shader graphs created for this tutorial.
  • Sprites: The sprite used as part of the instructions.
  • Textures: Texture maps for the game pieces and background.

Now, load the scene called TangramPuzzle from the Scenes folder.

Shader Graph in Unity for beginners

This is a simple game called Tangramwhich originated in China in the 1800s. The goal is to rearrange seven flat geometric shapes into stylized pictograms or silhouettes.

Enter Play mode in the Editor to test the demo game.

You can click and drag the shapes. Use the cursor keys to rotate the pieces. Turn and shift the pieces so they don’t overlap.

Can you figure out how to move the seven shapes into these patterns?

Shader Graph in Unity for beginners

Ok, the game technically works, but it doesn’t give you any visual feedback about your selected game piece.

What if you could make your game piece glow as the mouse makes contact? That might improve the user interface.

This is the perfect chance to show off Shader Graph!

Checking Pipeline Settings For Shader Graph

Shader Graph only works with the relatively new Scriptable Render Pipelineeither the High-Definition Render Pipeline or Lightweight Render Pipeline.

When creating a new project for use with Shader Graph, be sure to choose the correct template.

Creating a New Project

Your example project is already configured to use the Lightweight Render Pipeline. First, confirm in the PackageManager that you have the Lightweight RP and ShaderGraph packages installed by selecting Window ► PackageManager.

Then, select from the available versions and use the Update to button if necessary. The latest verified version is usually the safest choice.
Lightweight Render Pipeline

Once you’ve updated your packages, double-check that your pipeline settings are correct under Edit ► Project Settings.

In the Graphics tab, the Scriptable Render Pipeline Settings should read LWRP-HighQuality. This sets your project to use the highest default setting for the Lightweight Render Pipeline.

Close this window once you’ve confirmed that you’re using one of the Scriptable Render Pipeline assets.

Creating a PBR Graph

A material and a shader always work together to render a 3d mesh on-screen. So, before you can build your shader, you’ll need a material as well.

First, use the Create button in the Project view to generate a new material in the RW/Materials folder. Select Create ► Materialthen rename it to Glow_Mat.

Then, in the RW/Shaders folder, create a PBR Graph by selecting Create ► Shader ► PBR Graph. This is a shader graph that supports physically-based renderingor PBR.

Name it HighlightShaderGraph.

Create Shader Graph

The Glow_Mat material currently uses the default shader for the LightweightRenderPipeline called LightweightRenderPipeline/Lit.

Material Shader Select

Change it to use the new shader graph you just created. With Glow_Mat selected, click on the Shader dropdown at the top of the Inspector and select Shader Graphs ► HighlightShaderGraph.

The Glow_Mat material will change to a slightly lighter shade of gray but otherwise remain fairly drab. Don’t worry! You’ll remedy that soon.

Now, double-click the HighlightShaderGraph asset or click Open Shader Editor in the Inspector. This opens the Shader Graph window.

Shader Graph Editor

You should familiarize yourself with the main parts of this interface:

  • The main workspace is this dark gray area where you’ll store your graph operations. You can right-click over the workspace to see a context menu.
  • A node is a single unit of your graph. Each node holds an input, an output or an operation, depending on its ports. Nodes connect to one another using edges.
  • The Master node is the final output node of your graph. In this example, you’re using the physically-based rendering variant, also called the PBR Master node. You may recognize several properties, such as Albedo, Normal, Emission and Metallic, from Unity’s Standard Shader.
  • The Blackboard can expose certain parts of the graph to the Inspector. This allows the user to customize certain settings without needing to edit the graph directly.
  • The Main Preview interactively shows the current shader’s output on a sphere.

By connecting various nodes together, you can make a shader graphwhich Unity compiles and sends to the GPU.

Creating a Color Node

First off, give your shader some base color. This is done by feeding a color node into the Albedo component of the PBR Master Node. Right-click in the workspace area to create your first node from the context menu by selecting Create Node ► Input ► Basic ► Color.

Create New Node

Note that there are hundreds of nodes in the Create Node menu! While it may seem overwhelming at first, you’ll quickly become familiar with the most commonly used ones.

Next, drag the node around the workspace using its title bar. Then, drop it somewhere to the left of the PBR Master node.

The Color node allows you to define a single color. Click the color chip and select a nice red hue, such as R: 128, G: 5, B: 5.

To output the color to your PBR Master nodedrag the Out port into the Albedo port, which represents the base color of your shader.

Once you connect the nodes with an edge, you should see the Main Preview sphere turn red.

Color Node

Success! In shader writing, making a simple solid colored shader is the equivalent of coding Hello, world! :]

Though you might not realize it, you created your first custom shader!

Navigating the Interface

Although you only have a couple of nodes in your graph, now is a great time to get accustomed to the Shader Graph interface.

Drag the nodes around and notice that the edge stays connected between the Color’s output port and the PBR Master’s input port.

Nodes can contain different types of data. As you created a node that holds color input, you can also create a node representing a single number by selecting Create Node ► Input ► Basic ► Integer. You won’t actually do anything with this new node— it’s for illustration purposes only.

Connect Outputs

Connect the Integer Out port to the Alpha port of the PBR Master.

Your graph is still tiny, but now you have enough nodes to try out a few hotkeys. Select a couple of nodes and press these hoykeys:

  • F: frame the selected node or nodes.
  • A: frame the entire graph.

You can also use the buttons at the top of the window to toggle the Main Preview and Blackboard. The Show in Project button will help locate the current shader graph in the Project window.

Once you’re comfortable navigating your graph, do some cleaning. You only need the Color node and PBR Master node.

Right-click over the connection between the Integer and Master node and select Delete. That lets you disconnect the node from the graph.

Delete Edge

Likewise, you can delete the Integer node entirely. Right-click over the node and select Delete.

Delete Node

Once done, click the Save Asset button in the top left of the interface. Unity will save all your changes, then it will compile and activate the shader. This step is required every time you want to see your latest changes in the Editor.

Now, return to the Project window, then select the Glow_Mat material.

Material Preview

Because the shader is propagating to the material, the sphere in the Inspector preview should show up as red.

Now, drag the Glow_Mat material over one of the tangram pieces in the Scene window.

Assign Material

As you expected, your material and shader turn the mesh a nice, uniform red.

Adding a Glow Effect

If you want Glow_Mat material to have a more dramatic glow, edit the shader graph again.

Currently, you have the Color‘s output feeding into the Albedo of the PBR Master.

You can also drag another edge from the Out to the Emission. Now that same color is being used twice: Once for the base color and again for the emission color.

Emission Output

Output ports can have multiple edges, but input ports can only have one.

Now, switch the Mode dropdown in the Color node to HDR. This taps into the high-dynamic range of colors.

HDR Color Node

Next, edit the color chip. In HDR Modeyou get an extra option for Intensity. Click the +1 in the bottom swatch a couple of times or drag the slider to about 2.5. Then, save your changes and return to the Editor.

HDR Color Intensity

In the Editor, your game piece glows a bright red-orange. The post-processing in your scene is already set and enhances the high-dynamic range color.

Now, select the PostProcessing game object in the Hierarchy. The glow stems from the Bloom effect.

Next, open the Bloom parameters and adjust the Intensityor how strong the glow appears, and Thresholdor cutoff to start glowing. This example shows a value of 3 and 2respectively.

Bloom Intensity & Threshold

Wow, that’s a pop of color!
Emissive Bloom Effect

Making the Highlighter Script

You don’t want the game piece to glow all the time. You only want to enable it depending on the mouse position.

When the mouse hovers over a game piece, you’ll switch to the Glow_Mat material. Otherwise, the game-piece will display the default Wood_Mat material.

First, create a new C# script in RW/Scripts called Highlighter. This will help you swap between the two materials at runtime. Replace all the lines in your script with the following:

using UnityEngine;

// 1
[RequireComponent(typeof(MeshRenderer))]
[RequireComponent(typeof(Collider))]
public class Highlighter : MonoBehaviour
{
    // 2
    // reference to MeshRenderer component
    private MeshRenderer meshRenderer;

    [SerializeField]
    private Material originalMaterial;

    [SerializeField]
    private Material highlightedMaterial;

    void Start()
    {
        // 3
        // cache a reference to the MeshRenderer
        meshRenderer = GetComponent();

        // 4
        // use non-highlighted material by default
        EnableHighlight(false);
    }

    // toggle betweeen the original and highlighted materials
    public void EnableHighlight(bool onOff)
    {
        // 5
        if (meshRenderer != null && originalMaterial != null && 
            highlightedMaterial != null)
        {
            // 6
            meshRenderer.material = onOff ? highlightedMaterial : originalMaterial;
        }
    }
}

Let’s take a closer look at the script:

  1. The script can only be applied to an object that contains a MeshRenderer and a Collider component. This is controlled by adding [RequireComponent] attributes to the top of the script.
  2. These are references to the MeshRendereroriginalMaterial and highlightedMaterial. The materials are tagged with the [SerializeField] attribute, making them assignable from the the Inspector.
  3. In Startyou automatically fill in your MeshRenderer with GetComponent.
  4. You invoke EnableHighlight(false). This ensures that your non-highlighted material shows by default. The public method called EnableHighlight that toggles the renderer’s material is right below. It takes a bool parameter called onOff to determine the highlight’s enabled state.
  5. You guard to prevent any NullReference errors
  6. You use the ternary operator to save space.

Adding Mouse Events

Because you’ll apply this to game pieces with MeshColliders attached, you can take advantage of the built-in OnMouseOver and OnMouseExit methods. Add following after the EnableHighlight method:

    private void OnMouseOver()
    {
        EnableHighlight(true);
    }

    private void OnMouseExit()
    {
        EnableHighlight(false);
    }
 

When the Mouse is over a game piece, it will invoke EnableHighlight(true). Likewise, when the mouse exits the Collider, it will invoke EnableHighlight(false).

That’s it!

Save the script.

Highlighting the Game Piece

If you applied the Glow_Mat to any of the pieces in the previous sections of the tutorial, you need to switch all game pieces back to the Wood_Mat material in the Editor. You’ll use the Highlighter to enable the glow at runtime instead.

First, select the seven objects inside the Tangram transform that represents the individual game piece shapes. Then, add the Highlighter script to all of them at once.

Assign Highlighter Materials

Next, in the Original Material field, drag in the Wood_Mat material. Then, in the Highlighted Material field, drag in the Glow_Mat material. Finally, enter Play mode and check out your handiwork.

Not bad! When you hover the mouse over a tangram piece, it glows a bright, hot red. Move the mouse away from it and it returns back to its original wooden state.

Test Highlighter Script

You can still play the game normally, but now the highlight effect adds a little bit of visual interest, focusing the user’s attention.

Using Texture Nodes

Currently, the simple shader is a bright solid red color. You’re going to modify the shader so that it doesn’t lose the original wood texture. Instead, you’ll make the highlight appear as a glowing edge around the surface detail.

First, edit the HighlightShaderGraph by double-clicking it or selecting Open Shader Editor in the Inspector.

Delete the Color node, right-click on it, then select Delete. You’ll create everything from scratch.

Instead of a single color, you will plug in a texture by using the Sample Texture 2D node.

Create a node either from the context menu with a right-clickthen select Create Node or by using the spacebar hotkey. Select Input ► Texture ► Sample Texture 2D.

The Sample Texture 2D node reads color information from a texture asset and then outputs its RGB values.

Select a texture from the Texture input port. Click the dot next to the empty field to open the file browser.

Choose the WoodAlbedo texture asset.

Texture Node

Connect the Sample Texture 2D’s RGBA output port into the PBR Master Albedo port.

Voilà! Your preview sphere now shows the wood texture on the surface.

Shader Preview

If you add a normal map, you can add some more surface detail. First, create another Sample Texture 2D node by selecting Create Node ► Input ► Texture ► Sample Texture 2D.

Select the WoodNormal texture in the Texture input port.

Normal Node

Adjust the Type dropdown from Default to Normal.

Output the RGBA values into the Normal port of the PBR Master.

Shader Preview

The Main Preview sphere should now appear rougher. The normal map fakes small indentations and divots in the surface. This helps sell the appearance of wood grain.

Note: Each port’s data type is listed in parentheses next to the port. (T2) means the port is compatible with two-dimensional texture while (4) means the port uses a Vector4. Depending on context, Shader Graph is smart enough to ignore extra floating point values.

Adding a Fresnel Effect

Now that you have a base texture and normal map replacing the previous solid red color, let’s add the highlight effect using a different method.

Instead of making the entire object glow uniformly, you can confine the glow to only the edges. This can be accomplished with something known as the Fresnel effect.

Create a new node with right-click or using the spacebar hotkey, then select Create Node ► Math ► Vector ► Fresnel Effect.

This new node shows a sphere with a white glowing ring around its circumference. You can adjust the width of its halo using the Power input port. Click and drag the X label to the left of the field or enter specific numbers.

Larger values make the halo very thin, while smaller values make it very wide. You can use a value of 4 for a thinner rim glow.

Fresnel Effect Node

In order to pass this halo to your material, you connect the Fresnel Effect output to the Emission of the PBR Master.

Shader Preview

Your MainPreview now shows a wooden sphere with a bright white halo from the Fresnel Effect.

Note: The Fresnel effect is named for French physicist Augustin-Jean Fresnel. He observed that light makes surfaces very bright and mirror-like as the viewer approaches a near-grazing angle.

The Fresnel Effect

You can try it on your kitchen table. You’re using Unity’s version of this phenomenon to make the edges of your geometry glow.

Multiplying by Color

Adding some color to the glowing rim is as easy as doing some basic color math.

Create a new color node that will specify the color for the glowing ring. Use right-click
or spacebar to open the context menu, then select Create node ► Input ► Basic ► Color. Switch the color mode to HDR.

Select a color to represent your highlight color. For example, choose a nice bright green here, R:5, G:255, B:5.

Increase the Intensity to 3.5.
Color Intensity

You can’t plug the new color into the fresnel effect as it doesn’t have a color input. Instead, you’ll need to combine the fresnel output with the output from the color node. This is achieved by making use of a Multiply node.

Create a Multiply node with right-clickthen select Create node ► Math ► Basic ► Multiply.

Delete the existing edge between the Fresnel Effect and the PBR Master. Instead connect the Fresnel Effect Out to the A input of the Multiply node.

Connect the Color node’s Out to the B input of the Multiply node.

Multiply Node

Finally, connect the Multiply Out port to the Emission of the PBR Master port. Voilà! You can see the your bright green HDR color surrounding the Main Preview sphere.

Shader Preview

Remember you can use the Fresnel Effect Power to grow or shrink the halo. A smaller value of 1.5 gives you a broad green glow.

A value between 4 and 5 will work well for this sample game, but feel free to experiment with your own values.

Shader Preview

Save the shader graph and witch back to the Editor, you’re ready to see your HighlightShaderGraph in action.

Enter Play mode.

When you hover your mouse over a game piece, it retains its original wood texture. However, it now has a bright green glow around the edges. Once again, you can now play the game, only with a more subtle highlight.

Final Result

Adding Blackboard Properites

If you want to modify the look of the glow effect, you have to return to the Shader Graph editor window and make those changes. For example, you might want to grow or shrink the bright halo using the Fresnel Effect Power.

It’s not very convenient if you want to test out various changes. Fortunately, Shader Graph has the concept of Properties.

You can expose part of the graph publicly in the Inspector allowing you to make small changes interactively. This is done by making use of the Blackboard interface.

Return to to the Shader Graph and make sure the Blackboard is visible. Toggle the Blackboard button in the upper right if it is hidden.

Adding Base Texture and Normal Map properties

Now you’re going to expose the both the base texture and normal map to be accessible from the Inspector.

Click the + icon in the upper right of the Blackboard. Select Texture 2D from the dropdown. An entry should appear on the Blackboard. Rename it BaseTexture.

Texture 2D Property

Make sure exposed is checked. If you chose to expose a property, it’s public and available in the Inspector.

Property

To add the property to the graph, simply drag it by the label and drop it into the workspace. Leave it somewhere to the left of the Sample Texture 2D node.

Connect the BaseTexture port to the Texture input port on the SampleTexture 2D that plugs into the Albedo. This will replace the previous set value.

Repeat the same process for the Normal Map as well. Click the + icon and create a new Texture 2D. Rename it Normal Map.

Drag it into the workspace area and plug it into the Sample Texture 2D for the Normal map.

Normal Map Properties

Click Save Assetand return to the main Editor window.

Select the Glow_Mat material then take not of the two extra fields in the Inspector: Base Texture and Normal Map.

Because they currently have no Textures set, your preview window shows your green highlight over a gray sphere.

Material Preview

Select the WoodAlbedo and WoodNormal textures for the BaseTexture and NormalMaprespectively.

The wood textures now display correctly underneath the glowing edges.

Material Preview

Exposed properties allow the user to input data directly into the shader without needing to edit the shader graph itself. Experiment on your own with choosing different base texture and normal maps.

Adding Glow Size and Glow Color properties

Now you’re going to expose other types of properties on the Blackboard as well. For example, it would be useful to allow the user to adjust the Fresnel Effect Power value.

Click the + icon in the Blackboard and create a Vector1 property. This represents a single float parameter.

Rename it GlowSize.

You can limit what values can be entered in this property by converting it to a slider. Switch the Mode to Sliderthen set a Min of 0.05 and a Max of 6 to define the range. Set the Default value to 5.

Glow Size Property

Drag the GlowSize property into the workspace area. Plug the output port into the Fresnel Effect Power input.

Finally, allow the user to set the glow color through a property as well. Instead of creating the property from the Blackboard, you’ll convert an existing node in your graph.

Glow Color Property

Select the Color node, then right-click and select Convert to Property.

The Color node converts into a color property on the Blackboard that is no longer editable directly in the graph. Rename this property to GlowColor.

Final Shader Graph

Click Save Assetand return to the main Editor window.

Material Preview

Select the Glow_Mat material in the Project window. You should see a GlowSize slider and a GlowColor color chip available in the Inspector.

Material Preview

Edit your material values to your liking. Finally, enter Play mode to test your work.

Final Game

You now have a customizable highlight that you can tweak to your heart’s content!

Where to Go From Here

Congratulations! You can now create your very own shaders with Shader Graph!

With some creativity, you might surprise yourself with what else you can create. Want to make a cool, sci-fi laser beam or forcefield? You could adapt what you’ve done here into just the right shader.

Though there are literally hundreds of nodes to explore, this tutorial should have helped you to get started using Shader Graph.

If you have an questions or comments, please join the forum discussion below.


READ MORE – CLICK HERE

www.Red360.com.ve


from Red360.com.ve https://ift.tt/34PG3Cl
via Red360.com.ve