Videos

[Video] Unleash the Power of Raycasts with Dot Product

This Unity tutorial will show you how to dramatically improve your raycasts using the dot product of two vectors.

Unity’s built-in Raycast function is an extremely valuable tool. It allows you to cast a ray into the scene and determine whether or not it collides with anything. This is useful for common mechanics such as line-of-sight and collision detection.

But sometimes Raycast can be too precise, and using it can result in an unresponsive feel for the player. Luckily, we can use the dot product in cases like this to simply determine whether or not a ray is close to a target.

This unity tutorial uses basic object selection as an example to demonstrate how powerful this simple algorithm can be.

Learn more about Dot Product at https://betterexplained.com/articles/vector-calculus-understanding-the-dot-product

📦 Download the project at https://www.patreon.com/posts/27222309

Videos

[Video] Learn By Example – SOLID Principles in Unity (Part 2)

In this Unity tutorial, you’ll learn how to use the SOLID Principles through a simple example.

You don’t have to be an expert to write clean code. It just takes a little practice and discipline. The SOLID Principles are a set of 5 design principles that you can follow to write better code.

Follow along with this Unity tutorial to see the SOLID principles being used in a real-world example.

📦 Download the example project files here
❓ Got a Question? Check out this video’s Q&A here

QA

[Q&A] Learn By Example – SOLID Principles in Unity (Part 2)

This is the Q&A section for my video Learn By Example – SOLID Principles in Unity (Part 2)

I do my best to respond to every comment, but some questions require very detailed answers. As a result, I’ve created this page so Jason Storey and I have a place to provide detailed replies to some of the more complicated questions we receive.

Navigation

📺 Watch the video here

Question 1

How about native Unity classes like Transform? We can’t support the dependency inversion principle in such situations and it looks like a kind of a mess. What do you think?


Антон Смирнов

Jason Storey’s Answer

I wouldn’t be so sure about that! Dependency inversion is just a way of saying someone else will deal with that problem. The thing about using transforms. is that it is just another dependency. there are multiple ways to detach a dependency on it. lets look at a few.

Say you have a simple movement script. you want to set a direction to move in

void MoveTowards(Vector3 direction){
      transform.position += direction * speed;
}

ok. so that works. but you are dependent on the transform. but what about this.

void MoveTowards(Vector3 direction){
      rigidbody.AddForce(direction*speed);
}

this is moving the object but in a different way. so what if i had this

interface MoveMethod {
    void MoveTowards(Vector3 direction);
}

so which implementation does the MoveMethod use? does it matter? can you even tell if it uses a transform or a rigidbody?

now lets revisit the idea of transform dependence. Say you had some gameobject with this code in it

class Duck{
    MoveMethod _moveMethod;
    void Update(){
        var direction = GetPlayerInput();
         if(_moveMethod != null)
          _moveMethod.MoveTowards(direction);
    }
}

Do you see any mention of transform? rigidbody? maybe I want to use a tweening library to move. in short. a transform is just another “thing”. it is no more special than any other system in your code. it doesn’t need special treatment. it can be decoupled in just the same way. in fact it can even go the other way.

Imagine you wanted to get the position of objects but for some you want the position to be the feet, for others you want it to be the center of mass.

public class GameCharacter {
     Vector3 Position {get;set;}
}

You can use this code no problem. set the position get the position. no problem. but behind the scenes you could change it’s implementation from:

public class GameCharacter : MonoBehaviour {
     Vector3 Position {
         get => transform.position;
         set => transform.position = value;
      }
}

to:

public class GameCharacter : MonoBehaviour {
     public Vector3 PositionOffset = new Vector3(0,1,0);
     Vector3 Position {
         get => transform.position+PositionOffset;
         set => transform.position = value-PositionOffset;
      }
}

and the consuming code is none the wiser…

Question 2


With the current implementation, it feels very error prone for new users to start using the SelectionManager. It requires multiple additional scripts attached to the GameObject and the only way to see if the SelectionManager will work is to hit Play and parse the console messages. Is there a better way to handle this?


Mineeero

Jason Storey’s Answer

You bring up a good point, In real world terms you would follow a principle I call “Batteries Included” that states that even without configuration your code should work in a default state with additional configuration being optional, not required.

it avoids those confusing examples like you describe where someone is trying to use the code but doesn’t know what they need.

There are multiple possible ways to solve this problem. Lets look at some of them.

Requires Component

One option is to mark a script as being the one that composes the parts it needs to function with the RequiresComponent attribute. Which will automatically add the child classes it needs. This is a great help when you have specific implementations in mind but removes your ability to compose parts differently.

Default Implementation

A method I personally prefer is where you provide an implementation that does the bare minimum functionality. Lets take a simple example of achievements.

If you were making a game that was cross-platform and wanted to use google play for notifications on android, steam achievements on pc and use a custom implementation on apple devices you would have say, a GameScores script that would call into a Scoreboard to update it. lets have a look.

class GameScores {
     Scoreboard scoreboard;
     ScoreUI scoreScreen;
     Player player;
     Score score;
     
     public void GameOver(){
       scoreboard.SendScore(Player,score);
       scoreScreen.Show(score);

     }

}

In the above example you are calling to some external scoreboard to do whatever it wants with the score information and save it on whatever platform suits best. but if the scoreboard doesn’t exist you don’t want that to break the ability to show a score on the screen.

Also, you don’t want to be in a situation where someone tries to use your GameScores script but doesn’t know they need a scoreboard and everything breaks.

This is a prime candidate for the NullObjectPattern. What we want to do is effectively say “If you don’t provide me with a scoreboard I will use [X] by default” the important thing is though, it doesn’t matter what that [X] is, as long as it is a valid “scoreboard”.

That means it still counts even if it… does nothing!

Say we had:

class NoScoreBoard : Scoreboard {
  void SendScore(Player player,Score score){}
}

Now we can write something like

class GameScores {
     Scoreboard scoreboard;
     ScoreUI scoreScreen;
     Player player;
     Score score;
     
     public void GameOver(){
       GetScoreBoard().SendScore(Player,score);
       scoreScreen.Show(score);

     }

     ScoreBoard GetScoreBoard(){
         if(scoreboard == null) scoreboard = new NoScoreboard();
        return scoreboard;
     }

}

So even if the person using the code does not provide any implementation of a scoreboard at all, the code will work perfectly just… not post scores!

With this kind of a design what looks like requirements start to become “plugins” you can always provide a base level of implementation and expose an ability for the user to assign any new behavior they want.

Videos

[Video] Learn By Example – SOLID Principles in Unity

This Unity tutorial will show you how to use the SOLID principles to write code that’ll stand the test of time.

How many times have you abandoned a game because the project became a big pile of spaghetti code? You aren’t alone! Believe it or not, one of the leading causes of unfinished games is poorly written code.

But you’re in luck! This Unity tutorial will show you how to use the SOLID principles to write code that’s more flexible, maintainable, and easier to understand.

The SOLID principles are a set of five design principles that you can follow to start becoming a better programmer. They take the guesswork out of writing good, clean code!

📦 Download the example project files here

Videos

[Video] Selecting Object with Raycast – Unity Tutorial

This Unity tutorial will teach you how to select objects using raycasts by walking you through a simple example.

Ray Casting (or raycasting) is the process of using an invisible ray in order to solve a variety of problems in game development, such as intersections and collisions. This tutorial covers the ScreenPointToRay method which is one of a few ways to cast rays in Unity.

This tutorial was created in part with Jason Storey (apieceoffruit). Learn more about Jason by visiting http://www.firepanda.co.uk

📦 Download the example project here

Unity

Unity Job System Explained

There’s been a lot of buzz surrounding the Unity Job System over the past couple of years. But a lot of Unity developers still don’t seem to understand what it is or how it can benefit them.

In this post, I’m going to shed a little light on what the Unity Job System is, how it can help you, and what it looks like in practice.

Unity Capsicum: Performance by Default

Unity 2018 came with a new set of features that introduced the concept of performance by default. Code named “Capsicum”, this feature set includes the Unity Job System, Unity ECS, and the Burst Compiler.

When used correctly, Capsicum dramatically improves the performance of your game code.

But this post is about the Unity Job System. So, what is it? Well, at a high level, the Unity Job System allows you to introduce multithreading to your game code.

Improving Performance With Multithreading

Multithreading is a type of programming that takes advantage of a CPU’s capacity to process many threads at the same time across multiple cores.

A thread contains all of the contextual data needed to execute a set of instructions.

Traditionally, applications run all of their code on a single thread, called the “main thread”. But with multithreading you can write applications that execute multiple sets of instructions concurrently, or at the same time.

How Does Multithreading Improve Performance?

Multithreading is a key ingredient in improving the performance of your game code.

By splitting up CPU intensive operations into multiple processes that can all run at the same time, you can dramatically reduce how long those operations takes to execute. This results in massive improvements to loading times, frame rates, and battery life.

So, why do a lot of developers seem to avoid multithreaded code like the plague?

Why is it so Hard to Write Multithreaded Code?

Multithreaded code is complex and error-prone. For one, it’s easy to let your thread count get out of control, which can cause frequent context switching.

Context Switching

A Context Switch is a procedure that the CPU follows to change from one task to another. This happens automatically and it plays an important role in your computer’s ability to multitask.

During a context switch, the CPU has to store the state, or context, of the running task. This information is important because it helps the CPU avoid conflicts and also to resume the task later.

The problem is that context switches are expensive. And the time it takes to perform them adds up quickly. This becomes more of a problem as the number of active threads approaches and exceeds the number of available cores.

Race Condistions

Another complication of multithreaded code is the possibility of race conditions.

A race condition is a situation where your code behaves differently depending on the order in which it executes.

You can start threads in any order you want, but there’s no way to tell how they’ll run in relation to one another or when each one will finish finish. This indeterminism can result in unpredictable behavior and errors that are hard to debug.

This is especially true if two or more threads share and modify the same data.

Imagine a room with multiple light switches that all affect the same light bulb. If multiple people enter the room and randomly toggle light switches throughout the day, then it’s hard to predict whether the light will be on or off at any given moment.

On top of these examples, there are plenty of other factors that make writing multithreaded code a complex and difficult task. And that is where the Job System comes in.

The Unity Job System

The Unity Job System allows you to write multithreaded code easily and safely. It does this by creating jobs instead of threads.

A Job represents a units of work that the system can process as a series of steps.

When you a schedule job, the system places it into a special queue. Then, at some point during execution, a worker thread will pull the job out of the queue and execute it.

Worker threads are individual threads that are managed by the Unity Job. They complete jobs in the background so they don’t interrupt the main thread.

All you need to do is place your logic into custom jobs and then schedule them to run. The Job System will handle the rest, executing all of your jobs on seperate threads that are managed by Unity.

Why not Write Your own Multithreaded Code?

So how is this better than writing your own multithreaded code? I mean, under the covers, the Job System is still creating threads right? It’s still susceptible to all of the difficulties associated with multithreading.

The difference is that the developers who created the Unity Job System have gone to great lengths to ensure that their multithreaded code is iron clad.

For instance, the Job System will do it’s best to avoid context switching by only creating one worker thread per logical CPU core. This allows you to create as many jobs as you want (within reason) without having to worry about how it’ll affect the performance of your CPU.

The Job System also has a built-in mechanism for guarding against race conditions in the form of job dependencies. For example, if Job A needs to prepare some data for Job B, you can assign it as Job B’s dependency. That way Job A will always run first, and Job B will always have the correct data.

So what does a job look like and how do you schedule one? Let’s take a quick look at an example from Stalla3D’s Job System Cookbook Github Repo.

Using the Unity Job System to Modify a Mesh

In this example, the job uses Perlin Noise to modify the vertices and normals of a mesh during each frame. The job takes an array of vertices and normals, and floats that represent sine time, cosine time, and strength.

It’s execute method runs for each vertex in the mesh, and its corresponding normal. All it really does is calculate a new vertex and normal for the given index. And this is where the power of the Job System lies.

When this job is scheduled, Unity will queue up as many instances of it as it needs and the Worker threads will begin to execute them in parallel. The more logical cores your CPU has, the less time it’ll take for this job to complete.

I’ll go over an example in more detail in another post, but you can see by the Update method that scheduling this job is extremely simple. And the overall code footprint is much easier to understand and safer to write than low level multithreaded code would be.

Summary

So that’s the Unity Job System at a high level. It allows you to use multithreading in a way that safe, easy, and completely managed by Unity.

And when you combine it with Unity ECS and the Burst Compiler, you get extremely performant code that’s optimized by default.