Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Unity 5.x Shaders and Effects Cookbook
Unity 5.x Shaders and Effects Cookbook

Unity 5.x Shaders and Effects Cookbook: Master the art of Shader programming to bring life to your Unity projects

Arrow left icon
Profile Icon Zucconi
Arrow right icon
Free Trial
Full star icon Full star icon Full star icon Full star icon Half star icon 4.1 (9 Ratings)
Paperback Feb 2016 240 pages 1st Edition
eBook
S$53.98 S$59.99
Paperback
S$74.99
Subscription
Free Trial
Arrow left icon
Profile Icon Zucconi
Arrow right icon
Free Trial
Full star icon Full star icon Full star icon Full star icon Half star icon 4.1 (9 Ratings)
Paperback Feb 2016 240 pages 1st Edition
eBook
S$53.98 S$59.99
Paperback
S$74.99
Subscription
Free Trial
eBook
S$53.98 S$59.99
Paperback
S$74.99
Subscription
Free Trial

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Unity 5.x Shaders and Effects Cookbook

Chapter 1. Creating Your First Shader

This chapter will cover some of the more common diffuse techniques found in today's Game Development Shading Pipelines. In this chapter, you will learn about the following recipes:

  • Creating a basic Standard Shader
  • Migrating Legacy Shaders from Unity 4 to Unity 5
  • Adding properties to a shader
  • Using properties in a Surface Shader

Introduction

Let's imagine a cube that has been painted white uniformly. Even if the color used is the same on each face, they will all have different shades of white depending on the direction that the light is coming from and the angle that we are looking at it. This extra level of realism is achieved in 3D graphics by shaders, special programs that are mostly used to simulate how light works. A wooden cube and a metal one may share the same 3D model, but what makes them look different is the shader that they use. Recipe after recipe, this first chapter will introduce you to shader coding in Unity. If you have little to no previous experience with shaders, this chapter is what you need to understand what shaders are, how they work, and how to customize them.

By the end of this chapter, you will have learned how to build basic shaders that perform basic operations. Armed with this knowledge, you will be able to create just about any Surface Shader.

Creating a basic Standard Shader

Every Unity game developer should be familiar with the concept of components. All the objects that are part of a game contain a number of components that affect their look and behavior. While scripts determine how objects should behave, renderers decide how they should appear on the screen. Unity comes with several renderers, depending on the type of object that we are trying to visualise; every 3D model typically has MeshRenderer. An object should have only one renderer, but the renderer itself can contain several materials. Each material is a wrapper for a single shader, the final ring in the food chain of 3D graphics. The relationships between these components can be seen in the following diagram:

Creating a basic Standard Shader

Understanding the difference between these components is essential to understand how shaders work.

Getting ready

To get started with this recipe, you will need to have Unity 5 running and must have created a new project. There will also be a Unity project included with this cookbook, so you can use that one as well and simply add your own custom shaders to it as you step through each recipe. With this completed, you are now ready to step into the wonderful world of real-time shading!

How to do it…

Before getting into our first shader, let's create a small scene for us to work with. This can be done by navigating to GameObject | Create Empty in the Unity editor. From here, you can create a plane to act as a ground, a couple of spheres to which we will apply our shader, and a directional light to give the scene some light. With our scene generated, we can move on to the shader writing steps:

  1. In the Project tab in your Unity editor, right-click on the Assets folder and select Create | Folder.

    Note

    If you are using the Unity project that came with the cookbook, you can skip to step 4.

  2. Rename the folder that you created to Shaders by right-clicking on it and selecting Rename from the drop-down list or selecting the folder and hitting F2 on the keyboard.
  3. Create another folder and rename it to Materials.
  4. Right-click on the Shaders folder and select Create | Shader. Then right-click on the Materials folder and select Create | Material.
  5. Rename both the shader and material to StandardDiffuse.
  6. Launch the StandardDiffuse shader in MonoDevelop (the default script editor for Unity) by double-clicking on it. This will automatically launch the editor for you and display the shader code.

    Note

    You will see that Unity has already populated our shader with some basic code. This, by default, will get you a basic Diffuse shader that accepts one texture. We will be modifying this base code so that you can learn how to quickly start developing your own custom shaders.

  7. Now let's give our shader a custom folder from which it's selected. The very first line of code in the shader is the custom description that we have to give the shader so that Unity can make it available in the shader drop-down list when assigning to materials. We have renamed our path to Shader "CookbookShaders/StandardDiffuse", but you can name it to whatever you want and rename it at any time. So don't worry about any dependencies at this point. Save the shader in MonoDevelop and return to the Unity editor. Unity will automatically compile the shader when it recognizes that the file has been updated. This is what your shader should look like at this point:
    Shader "CookbookShaders/StandardDiffuse" {
      Properties {
        _Color ("Color", Color) = (1,1,1,1)
        _MainTex ("Albedo (RGB)", 2D) = "white" {}
        _Glossiness ("Smoothness", Range(0,1)) = 0.5
        _Metallic ("Metallic", Range(0,1)) = 0.0
      }
      SubShader {
        Tags { "RenderType"="Opaque" }
        LOD 200
        
        CGPROGRAM
        // Physically based Standard lighting model, and enable shadows on all light types
        #pragma surface surf Standard fullforwardshadows
    
        // Use shader model 3.0 target, to get nicer looking lighting
        #pragma target 3.0
    
        sampler2D _MainTex;
    
        struct Input {
          float2 uv_MainTex;
        };
    
        half _Glossiness;
        half _Metallic;
        fixed4 _Color;
    
        void surf (Input IN, inout SurfaceOutputStandard o) {
          // Albedo comes from a texture tinted by color
          fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
          o.Albedo = c.rgb;
          // Metallic and smoothness come from slider variables
          o.Metallic = _Metallic;
          o.Smoothness = _Glossiness;
          o.Alpha = c.a;
        }
        ENDCG
      } 
      FallBack "Diffuse"
    }
  8. Technically speaking, this is a Surface Shader based on physically-based rendering, which Unity 5 has adopted as its new standard. As the name suggests, this type of shader achieves realism by simulating how light physically behaves when hitting objects. If you are using a previous version of Unity (such as Unity 4), your code will look very different. Prior to the introduction of physically-based shaders, Unity 4 used less sophisticated techniques. All these different types of shader will be further explored in the next chapters of this book.
  9. After your shader is created, we need to connect it to a material. Select the material called StandardDiffuse that we created in step 4 and look at the Inspector tab. From the Shader drop-down list, select CookbookShaders | StandardDiffuse. (Your shader path might be different if you chose to use a different path name.) This will assign your shader to your material and make it ready for you to assign to an object.

    Note

    To assign a material to an object, you can simply click and drag your material from the Project tab to the object in your scene. You can also drag a material on to the Inspector tab of an object in the Unity editor to assign a material.

The screenshot of an example is as follows:

How to do it…

Not much to look at at this point, but our shader development environment is set up and we can now start to modify the shader to suit our needs.

How it works…

Unity has made the task of getting your shader environment up and running, which is very easy for you. It is simply a matter of a few clicks and you are good to go. There are a lot of elements working in the background with regard to the Surface Shader itself. Unity has taken the Cg shader language and made it more efficient to write by doing a lot of the heavy Cg code lifting for you. The Surface Shader language is a more component-based way of writing shaders. Tasks such as processing your own texture coordinates and transformation matrices have already been done for you, so you don't have to start from scratch any more. In the past, we would have to start a new shader and rewrite a lot of code over and over again. As you gain more experience with Surface Shaders, you will naturally want to explore more of the underlying functions of the Cg language and how Unity is processing all of the low-level graphics processing unit (GPU) tasks for you.

Note

All the files in a Unity project are referenced independently from the folder that they are in. We can move shaders and materials from within the editor without the risk of breaking any connection. Files, however, should never be moved from outside the editor as Unity will not be able to update their references.

So, by simply changing the shader's path name to a name of our choice, we have got our basic Diffuse shader working in the Unity environment, with lights and shadows and all that by just changing one line of code!

See also

The source code of the built-in shaders is typically hidden in Unity 5. You cannot open this from the editor like you do with your own shaders.

For more information on where to find a large portion of the built-in Cg functions for Unity, go to your Unity install directory and navigate to Unity45\Editor\Data\CGIncludes. In this folder, you can find the source code of the shaders shipped with Unity. Over time, they have changed a lot; UNITY DOWNLOAD ARCHIVE (https://unity3d.com/get-unity/download/archive) is the place to go if you need to access the source codes of a shader used in a different version of Unity. After choosing the right version, select Built in shaders from the drop-down list, as shown in the following image. There are three files that are of note at this point—UnityCG.cginc, Lighting.cginc, and UnityShaderVariables.cginc. Our current shader is making use of all these files at the moment:

See also

Chapter 10, Advanced Shading Techniques, will explore in-depth how to use GcInclude for a modular approach to shader coding.

Left arrow icon Right arrow icon

Key benefits

  • This book will help you master the technique of physically based shading in Unity 5 to add realism to your game quickly through precise recipes
  • From an eminent author, this book offers you the fine technicalities of professional post-processing effects for stunning results
  • This book will help you master Shader programming through easy-to-follow examples to create stunning visual effects that can be used in 3D games and high quality graphics.

Description

Since their introduction to Unity, Shaders have been notoriously difficult to understand and implement in games: complex mathematics have always stood in the way of creating your own Shaders and attaining that level of realism you crave. With Shaders, you can transform your game into a highly polished, refined product with Unity’s post-processing effects. Unity Shaders and Effects Cookbook is the first of its kind to bring you the secrets of creating Shaders for Unity3D—guiding you through the process of understanding vectors, how lighting is constructed with them, and also how textures are used to create complex effects without the heavy math. We’ll start with essential lighting and finishing up by creating stunning screen Effects just like those in high quality 3D and mobile games. You’ll discover techniques including normal mapping, image-based lighting, and how to animate your models inside a Shader. We’ll explore the secrets behind some of the most powerful techniques, such as physically based rendering! With Unity Shaders and Effects Cookbook, what seems like a dark art today will be second nature by tomorrow.

Who is this book for?

Unity Effects and Shader Cookbook is written for developers who want to create their first Shaders in Unity 5 or wish to take their game to a whole new level by adding professional post-processing effects. A solid understanding of Unity is required.

What you will learn

  • Understand physically based rendering to fit the aesthetic of your game
  • Enter the world of post-processing effects to make your game look visually stunning
  • Add life to your materials, complementing Shader programming with interactive scripts
  • Design efficient Shaders for mobile platforms without sacrificing their realism
  • Use state-of-the-art techniques such as volumetric explosions and fur shading
  • Build your knowledge by understanding how Shader models have evolved and how you can create your own
  • Discover what goes into the structure of Shaders and why lighting works the way it does
  • Master the math and algorithms behind the most used lighting models

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Feb 26, 2016
Length: 240 pages
Edition : 1st
Language : English
ISBN-13 : 9781785285240
Vendor :
Unity Technologies
Languages :
Concepts :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Feb 26, 2016
Length: 240 pages
Edition : 1st
Language : English
ISBN-13 : 9781785285240
Vendor :
Unity Technologies
Languages :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just S$6 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just S$6 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total S$ 216.97
Unity 5.x Shaders and Effects Cookbook
S$74.99
Unity UI Cookbook
S$74.99
Unity 5.x Game AI Programming Cookbook
S$66.99
Total S$ 216.97 Stars icon

Table of Contents

11 Chapters
1. Creating Your First Shader Chevron down icon Chevron up icon
2. Surface Shaders and Texture Mapping Chevron down icon Chevron up icon
3. Understanding Lighting Models Chevron down icon Chevron up icon
4. Physically Based Rendering in Unity 5 Chevron down icon Chevron up icon
5. Vertex Functions Chevron down icon Chevron up icon
6. Fragment Shaders and Grab Passes Chevron down icon Chevron up icon
7. Mobile Shader Adjustment Chevron down icon Chevron up icon
8. Screen Effects with Unity Render Textures Chevron down icon Chevron up icon
9. Gameplay and Screen Effects Chevron down icon Chevron up icon
10. Advanced Shading Techniques Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.1
(9 Ratings)
5 star 66.7%
4 star 0%
3 star 11.1%
2 star 22.2%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Nicolas Dec 05, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
all is ok!!!
Amazon Verified review Amazon
Cid Jan 16, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I wish I had this book when I first started writing Unity shaders!
Amazon Verified review Amazon
Eldoir May 31, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Perfect reading for a beginner in shaders. Finally, someone explained it simply from scratch ! Alan is a great teacher. Don't hesitate to check on his website for other great tips about shaders, Unity, or other interesting stuff. (I was not paid to write this, I really mean it !)
Amazon Verified review Amazon
Bill Jones Apr 23, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
First I have to just say I love the cover for some reason, I suppose it fits the bill for shaders and so does the book. Absolutely loved the recipes in this book. However if you want to get something setup to test with this book also worked well for that given the approach the author used to get the test off the ground, you can see the pipelines, texture mapping, and rendering all in one! :)
Amazon Verified review Amazon
Edmon Dantés Oct 16, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Recomendado para personas con un conocimiento moderado de matemáticas con ganas de aprender las bases y metodologías de la programación de Shaders en Unity 5He quedado muy satisfecho con los temas que se tratan y como se explican paso por paso.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.