Book Image

Unity 2021 Shaders and Effects Cookbook - Fourth Edition

By : John P. Doran
Book Image

Unity 2021 Shaders and Effects Cookbook - Fourth Edition

By: John P. Doran

Overview of this book

Shaders enable you to create powerful visuals for your game projects. However, creating shaders for your games can be notoriously challenging with various factors such as complex mathematics standing in the way of attaining the level of realism you crave for your shaders. The Unity 2021 Shaders and Effects Cookbook helps you overcome that with a recipe-based approach to creating shaders using Unity. This fourth edition is updated and enhanced using Unity 2021 features and tools covering Unity's new way of creating particle effects with the VFX Graph. You'll learn how to use VFX Graph for advanced shader development. The book also features updated recipes for using Shader Graph to create 2D and 3D elements. You'll cover everything you need to know about vectors, how they can be used to construct lighting, and how to use textures to create complex effects without the heavy math. You'll also understand how to use the visual-based Shader Graph for creating shaders without any code. By the end of this Unity book, you'll have developed a set of shaders that you can use in your Unity 3D games and be able to accomplish new effects and address the performance needs of your Unity game development projects. So, let's get started!
Table of Contents (16 chapters)

Implementing Heatmaps with arrays

One characteristic that makes shaders hard to master is the lack of proper documentation. Most developers learn how to use shaders by messing around with the code, without having a deep knowledge of what's going on. The problem is amplified by the fact that Cg/HLSL makes a lot of assumptions, some of which are not properly advertised. Unity3D allows C# scripts to communicate with shaders using methods such as SetFloat, SetInt, and SetVector. Unfortunately, Unity3D doesn't have a SetArray method, which leads many developers to believe that Cg/HLSL doesn't support arrays either. This is not true. This recipe will show you how it's possible to pass arrays to shaders. Just remember that GPUs are highly optimized for parallel computations, and using for loops in a shader will dramatically decrease its performance.

For this recipe, we will implement a heatmap, as shown in the following screenshot:

Figure 12.17...