Complete Beginners Guide to Unity C# Game Development | Christopher Navarre | Skillshare

Complete Beginners Guide to Unity C# Game Development

Christopher Navarre, Software Instructor

Play Speed
  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x
50 Lessons (8h 1m)
    • 1. Unity Course Introduction

      1:34
    • 2. What are Components vs GameObjects Explained

      5:46
    • 3. Differences between Canvas GUI Elements vs Gameplay Objects

      4:57
    • 4. All UI Components Explained

      12:43
    • 5. MonoBehaviours and Unity Lifecycle Hooks (Update, Fixed Update, LateUpdate, Start, Awake)

      5:17
    • 6. Basic C# - Random Color Changing Script

      8:01
    • 7. Random Color Change on Timer Tracking deltaTime in Script

      4:27
    • 8. Introduction to Scriptable Objects

      9:51
    • 9. Making Items in Scriptable Object Inventory System

      4:23
    • 10. Referencing Scriptable Object Assets and Nesting Scriptable Objects

      3:33
    • 11. Scriptable Object Shop Inventory and Showing Items to Players

      8:53
    • 12. Aseprite vs Pyxel Edit Pixel Art Animation & Tile Tool Comparison

      10:24
    • 13. How to Import and Create Custom Color Palettes

      2:32
    • 14. Best Way to Import 2D Sprites & Pixel Art

      6:48
    • 15. Control Sprite Rendering Order (Which 2D Objects Show in Front)

      4:14
    • 16. How to Create Shadows for 2D Game Sprite Images

      11:44
    • 17. How to Setup Baked Lighting to Illuminate 2D Pixel Sprite Games

      6:12
    • 18. Make a Simple 2D Tiled Background

      4:34
    • 19. How to Hide Part of Sprite Animation with Sprite Mask

      4:25
    • 20. How to Move Left and Right with Input & Rigidbody 2D Forces

      15:48
    • 21. Limit Run Speed Velocity Cap

      7:59
    • 22. Jump Forces and How to Check If Player is Standing on Ground Collider

      15:11
    • 23. Collider.Cast - Checking for Collisions

      4:05
    • 24. Fireball Spritesheet Animation Setup

      7:14
    • 25. Moving Fireballs with Collision Detection

      18:27
    • 26. Projectile Physics - Curved Path and Returning Projectiles

      32:51
    • 27. How to Move a Kinematic Body with an Animation Curve

      5:45
    • 28. Making a Main Menu - Setup

      10:08
    • 29. Coding Main Menu Buttons

      11:09
    • 30. How to Make Load Menu Popup & Close Menu Buttons

      5:06
    • 31. Pause Menu with Prefabs & Singleton Menu Manager Script [Part 1] Setup

      6:07
    • 32. Pause Menu Prefab & Menu Manager [Part 2] MonoBehaviour Manager Script

      16:05
    • 33. Menu Prefabs & Menu Manager [Part 3] Singleton System

      10:34
    • 34. Menu Prefabs & Manager [Part 4] Decoupling Data from Singleton System

      11:32
    • 35. Menu Prefabs & Singleton Manager Part 5 Control UI Menus in Singleton System Code

      18:13
    • 36. Customize GUI Locations During Gameplay in Options Menu

      19:19
    • 37. Smooth Pixel Perfect 2D Movement

      4:45
    • 38. How to Spawn Copies of Enemies or Projectiles at Mouse Cursor Point

      7:42
    • 39. Custom Unity Events and Delegate Actions in Inspector

      4:45
    • 40. Animated 2D Door Open Close on Trigger

      8:39
    • 41. Spawn GameObjects when Scene Loads through Code

      5:55
    • 42. GUID Manager Unique IDs for Maintaining Changes to Game Objects During Game Play

      20:34
    • 43. How to Save and Load with Save Files

      16:14
    • 44. How to Create Character Talking Blip Sound Effects in BFXR for Classic Style Games

      6:22
    • 45. Introduction to Zenject

      12:45
    • 46. Dependency Injection for Spawning Game Objects after Scene Load

      14:02
    • 47. Game Settings as Scriptable Object Installer

      7:59
    • 48. Basic Unit Testing Setup with Assembly Definition Files

      12:13
    • 49. PlayMode Tests for GameObjects in Test Scene

      8:12
    • 50. Unit Testing with Zenject Dependency Injection

      15:07
46 students are watching this class

About This Class

Learn the ins and outs of building 2D games in Unity 2018 from the ground up. We will cover working in the engine, GameObjects & Components in detail, many coding topics, and building art assets from a technical perspective.

We will start from basics and there will be example scripts for you to download, test, and use if you wish throughout many of the tutorials provided in the course.

With a focus on coding, I will be showing you advanced techniques such as Dependency Injection to make your scripts more loosely coupled and easier to make changes to later on and Unit testing through the Unity Test Runner.

Several external tools will be covered as well to help you in creating your game (Pyxel Edit for Pixel Art, BFXR for Sound Effects, etc).

Relevant Course Materials (Scripts, Assets) will be uploaded her for you to use https://drive.google.com/open?id=1Z4sJ8BR4NSXPiltno0O1RjuC4Ny4_atD

Note that not every tutorial will have it's own assets

Here are some of the Unity basics that will be covered in the course

  • Rigidbodies and 2D kinematic game physics
  • Adding, using, and manipulating components on game objects
  • Workflows in Unity and learning how to work more efficiently
  • Manipulating audio sources for sound playback during events and animation
  • Adding lighting to 2D sprite objects in the game engine.
  • Using the Unity Tilemapping Tools to Create Game Maps with easy collision setup
  • Step A to Z in Creating Prefabs for your game like a Giant Animated Fireball

Here are some of the coding topics covered in the course

  • Collision checking for walls and event triggers
  • UI Menus - How to create and navigate between menu using the UI components available inside of unity
  • Saving and Loading Game Data to Permanent or Temporary Files on Any Platform
  • Odin Inspector - a Premium addon that makes it easy to design inspectors for your scripts so designers can make changes to your game and also opens up serialization for important C# objects like Dictionaries.
  • Managing character inventories including items and money
  • Remembering the state of objects in the game when the player leaves and reenters a scene
  • How to Use Scriptable Objects - Storing important game data like settings in an asset file that you can easily edit with the Unity inspector
  • Custom unity events and making outside scripts react to them
  • Enemy and Projectile spawning scripts
  • Unit Testing and Scene Testing with the Unity Test Runner
  • Dependency Injection with Zenject


Music from https://filmmusic.io
"Beauty Flow" by Kevin MacLeod (https://incompetech.com)
License: CC BY (http://creativecommons.org/licenses/by/4.0/)

Transcripts

1. Unity Course Introduction: Hello, everybody, Chris Here and in this video, I'd like to explain to you what you expect from this eight hour plus course on game development in the unity engine. So as implied from the course title. This is a programming focused course, but we will also be touching. On Related to T are an asset. Subjects such as introducing a surprise as a tool for making straight characters and tiles for two D games, and also the effects are as a free sound generation tool. The bulk of the course is going to be showing core unity elements of games such as game objects components, which attached to game objects in order to give him some functionality. Graphical user interfaces, which would include things like buttons, entitle screens and, of course, the programming aspect. How to fight C Sharp scripts toe add functionality to all of those components of your unity game and bring them together with actually adding in scripted functionality. Since this is a two D game course, you can expect there to be specific topics like how to manage, rendering order of sprites and creating lighting and shadows specific to two D games. You also learn some two D game physics concepts such as rigid bodies, which will actually allow a character to interact with the physics engine, checking for collisions between objects and tips for getting smooth character movement, especially if you happen to be doing a pixel art style game Towards the end of the course, we're going to be covering more scripting heavy topics, such as coding out a GeoEye game menu, implementing saving and loading into your game. So if all of this sounds like something that you're interested in, then I hope you'll join us on the course and learn a lot about how to make your own two D games in the unity game engine. 2. What are Components vs GameObjects Explained: Hello, everybody, Chris Here and in this video, I wanted to cover the basics of game objects, model behaviors and components inside of unity, the insight of unity when you're creating a scene, everything that will exist inside of the hierarchy, whether you created while you're editing the scene or whether you spawned those objects with a script. When the game is actually running, every thing or object is going to be put under the scene in terms of a higher arc. And since we're building games, we refer to all of those objects inside of the scene as game objects. Now, game objects can be things that will interact with other objects in the world, such as enemies, players or tiled walls. But a game object can also be something that is specific to the graphical user interface or the U I off your game. What a game object can also be something that does not interact with your game world but rather exists on overlay called the graphical user interface or the U I. But regardless of if it's directly part of your game or just for showing information to your player, all of those elements will be considered game objects within the game. Now what does a game object have attached to it? To demonstrate briefly, I'm going to right, click on the hierarchy you and go down to you I and will create some kind of you I components that we can compare a regular game object to a U I game object. Essentially, they are the same, except that you I game objects are attached with this component called direct transform instead of any other game object not attached to the U I of the canvas here, which would just contained a regular transform. Aside from that, any game object is able to have different components, like this camera component you see here an audio listener or is dropped down you. I component an image, a drop down script. All of these extra elements are called components inside of unity. Essentially what that makes a game object. Inside of unity is a container for components that will interact on the game object. But the game object itself is required to have a transform at the very minimum, and you can see appear at the top that there is always some information that's associated with game objects such as a tag layer which game object is on, and the check box up here in the top left of the inspector for whether or not the game object is enabled or disabled within the scene. How things work in unity is that you start by creating a simple game object shell, and then when you want to add behavior or information to that game object that could be referenced in other scripts. Then you add components to the game object. And the easiest way to do that in the Inspector over here, like the game object in the hierarchy, go over to the inspector, and then you add component. And you can choose from any mono behavior, script or any of the default components that exist inside of unity, such as a box collider for determining collisions. Now I mentioned Amano Behavior script. The default way of doing things in unity if you're trying to write scripts, is to do things and c sharp and then in your script you inherit from a class called mono behavior. So what you need to know about a model behavior for right now is that it affords certain functionality like being able to reference the transform component, and it's positioned. Rotation and scale making have some useful information to you script. But the critical aspect of it being a model behavior script is that you can attach it as a component to a game object. And by doing that, you can have the game object to use that script and to be able to call the methods that you write within that script class do. For instance, you can see here in the Scripts folder of this project. I have a script here called Game Menu, and this game menu is a class, meaning you can create an object from it. And this class of game menu inherits from mono behavior. That means this game menu script can be attached as a component to any game object. And by attaching one of these scripts, we can easily have that game object around the functionality. So you might be creating scripts Ramana behavior to do things like manage the else of an enemy to manage the inventory off a player or to handle two D movement and collisions, it's possible to cram pretty much everything you want an object to do into one script if you want. You can also decide to decouple functionality so you might separate off the things you want a player object to do into separate scripts. They might have one script for inventory, one script for movement and so on and so forth. So if I wanted to quickly create a new script, I can right click over here and go down to see Sharp script right Click. Create the sharp script. I'll leave it at the default name Newbie Weapon. You can see that when you create a new C shop script in this way, it's over the inherited model behavior. It doesn't really do anything, but it does, right These empty methods for you. Eso start an update. They occur in the life cycle of unity so you can have certain things happen at certain times during your games operation. Okay, so now if we want to attach this new script to a game object, we can drag the script in. And as long as it's a model, behavior should be able to pop it right in and remove scripts by clicking on the gear over here and then remove component and we can also search for the component, even ones that we created ourselves by typing in the name of the script and adding it end there. 3. Differences between Canvas GUI Elements vs Gameplay Objects: the one more thing I want to point out about you I game objects is that they must exist under a canvas game object so you can see this canvas was automatically created when we added in a drop down You I to our game. And this canvas game object contains a canvas component, a canvas scale, a component and a graphic. Ray Kaster. All these components are added by default, and we can usually leave them as the default settings. But what this allows toe happen is our wrecked transform You I game objects to render on the campus. So when we have you, I components added to the canvas. The main difference is that thes you I components are never going to move with respect to the camera. So if I, uh, put this drop down menu in the bottom right hand corner over here inside the canvas, then when we go to game, it's gonna draw on the screen, and we do have a camera in the scene. It's not following anything at the moment. We would have to write a follower script for that. But if the camera ever moves inside the scene, these you I components will not move. They don't have any perspective or viewing angle with respect to the camera and the scene, They are simply a layer that goes on top of things. So you would use the canvas often for drawing things like how much money's player has, how much health is left, possibly what weapons or items they have equipped. So for any non canvas you I game object if I added to the scene and let's adjust the position a little bit and maybe change this right so we can actually see it in there. So for all of these other game objects that exist outside of the canvas, whether or not they draw on screen depends completely on whether the camera is looking at them or not. So if I go to this game tab over here, but I adjust the position off the camera, you can see Oh, the you I doesn't move. But the object appears to move because the camera is cameras not looking at this object it And of course, you can move the sprites as well, changing their position within the game world, including Z access. If you ever are working in a three d game and not a to D came. Aside from that, there's a few minor differences between any game object that might appear on the Envious rather than the game itself. Another thing that you might notice here is that when a item has erected transform, it works at a different scale than objects in the game world itself. So you can see here. These game objects are working in terms of game units, and a game unit is basically determined by what size you have this bright drawing at. So if we take a look at some straight sheets that I've imported, if I set the pixels per unit on that spreadsheet to 512 then that means 512 pixels of this Sprite is Theo equivalent to one unit in the game world, but then items inside of the U. I are based on pixel values, and this pixel values well. The size is going to be relative to the screen size. So if you have a saying that 640 pixels by Thesixties picks us like I currently have it set up over here and you can define your own custom sizes by clicking on this drop down and going to the bus. That means if I take one of these canvas elements and I set the value to be equal to the screen size, then it will draw itself all the way across the screen. That also means if I said something like the position x 2 50 we're talking about 50 pixels away from the anchor point you can see here anchor points. I currently have it set to the centre, so it's 50 pixels off center, though he would be the center roughly. And then this is the center area for the game objects. So it's drawing about right here, which is what we would so beyond that, there is a couple minor differences between game objects outside of the canvas and those inside. For one thing, if you want to render an image and the canvas, use an image script, which is specifically for drawing on the canvas. I you I components are also gonna have these canvas vendor components attached to them so they can render on the envious. And when you want to render an image as a two d Sprite image on a game object that's in the game world. Use a Sprite render instead, so you don't use image on actual game players or game enemies. You use image when you're talking about the canvas by. But aside from that, all game objects in your scene followed the same basic structure. It's all about adding components to give them extra functionality and accessing the values . And those components, like the transform in order to achieve what you want inside of the game would, if that's moving, some things position and you get scale making it visit boy invisible or changing a value on one of the components like a health total. 4. All UI Components Explained: Hello, everybody, Christer And in this video for unity, I wanted to explain to you guys all of the u I components, how they interact together and what each of them are used for. So when I'm talking about you, I components inside of unity. I'm of course referring to If you were to right, click and go down here to you I all of the different game objects you can create that air for building your in game. You I That's separate from the actual actors, that player, the enemies off that, but rather the stuff that displays on screen like a gooey interface. Another way you can create these you I components in any other game object is to go up to the game object menu, and then you would choose you. I and you have pretty much the same options available here. So for this video, at least we're going to be sticking toothy. Default You. I components for unity and not covering any thing from an Adam like text mash pro. Um, but yeah, let's go ahead and get into it anyway. So the first item I have in this game hierarchy created already is the canvas. The canvas is the base. You, I component because everything else that's your component, like about to know an image, at least image that's for you. I needs to be added on top of the canvas. The canvas is going to be where you I renders. So the important thing to know about the canvas you, I component, is that it's where all of the other you I components go on top off. Now the canvas itself doesn't really do much, has a couple things on it, such as the graphic rate caster, which allows things like mouse clicks to interact with you. I components, but every other year I component needs to be added on to this as a base. So next up is panels and panels of basically boxes that you can add extra stuff under. You can add any game object is a child to another game object. You can see here that buttons have text components by default as a child, but the panel basically provides you with an image that by default is this kind of boring. Great. But you can change that to any other kind of pattern or image that you want as the panel background. And then what you generally do is you add extra components like a text box for a title on to that panel, and your panel would then become a menu object. So one thing I like to dio is if I have buttons or key bindings that would open up a game menu, I would actually specifically be targeting the panel itself. Because if you set a panel or basically apparent game object, Teoh active or not, act if you can show or hide everything beneath it. Art once so panels tend to be a good object to rename to a menu and then just stick everything else that is contained in that menu. Been meet Okay, so next up is the text box. So this is for displaying text, not for entering text, like an import field with a text box. You can add in whatever text you wanted to display, including hitting enter when you want a new line. Now you notice that by default you may have text that does not properly display on that text box, and that may be due to your vertical overflow setting, where its trunk it's going to just not show the text that can't fit in the box. But if you do overflow, then it will just go over the line and show any way you can also change the font size. If you want to precise everything, align it to the center both horizontally and vertically and, of course, changing the color of the tax located inside of it. So generally your use text elements for things like titles or labels for other items such as and input bucks. But just know that it's only for display. You can change what it says in script, but you will never get user import directly on a text you I component. So next up is an image component. Whenever you need to display an image on your you, I something like a logo or any graphics that you need to pop up there. You can just pop in a image you, I component, which will have an image script. You might notice that the panel also has an image script, but it's defaults a different. This is more for backgrounds, and the image is set up with the expectation that it's more like just a general graphic. He put on and not a box to contain everything. So when you have the image script attached to a game object, it's gonna be sprites located inside of the script. So my understanding of the difference between an image in a raw image here is the images will take the image and display it as a sprite, which gives it some extra functionality, being generally better for things like animating it and being easy to work with. But then a raw images a little bit faster, because it doesn't have the extra overhead of all that Sprite functionality. So raw images can be used for stuff like basic textures when you don't need to animate it or anything of that nature. But honestly, you could probably just get away with making everything an image. Unless performance really matters to you, though, you can probably get away with just using image components in all cases. Really, I haven't run into any situation yet where using images which might displayed a suspect has actually slowed everything down enough to be noticeable. Okay, so next up is button and you'll be using buttons a lot because buttons allow you to attach a on script event delegate down here. So basically, you can drag any object that has a script into here, and then you can run one of the functions on that object, and then you can run one of the functions from that game object or the script attached to it. And basically what that'll mean is, when the button is clicked, it's gonna run. All of these functions that are listed be low, and you can, of course, have multiple functions. So much is a really useful when you want to do something like enter a new menu, you can use our button to do that. And then you just enabled the menu by game objects active. But really, as long as you can reference a game object that has a script attached to it, you can basically make the on click events. Do whatever you want. You could also have buttons on screen from mobile games for things like attacking enemies or or making an in game purchase, whether that's for the cash shop or part of the game itself. So budgets of super useful and as for the text that's displaying their buttons always come default with a text component as a child, it's not mandatory. You can just delete it like that if you want. But the text basically to title the Botton in that players know what that's going to be about. I'm just is easily, though you could replace it with an image on top of it as well. Basically, whatever floats your boat. Okay, So next is the taco component. This is where you have basically a true false Yes, no question or option. And you want them to be able to toggle or switch between those two options basically on or off. So if you have a BOOLEAN value or you want to control a Boolean value and script, this is really useful. So it might be like enable music and then you would use a taco. Um, because you just wanted to be on or off situation. Now you can see here has child elements. They've gotta image component down here, and another image for the check Mark Onda, Also the label, which is just a tax component to label the button. So it's basically four components built into one. But using the taco can make it a little bit more straightforward and whenever you want the taco to change something whenever you get the check box on value changed works very similar to on Click just instead of when the button is clicked. It's whenever this check box is marked. So next we have drop downs, which offer drop down menus. So the idea of the drop down menus is that it will allow the user of the player in this case, too. Choose from a few different options. So when you drop this down, it's going to expand this template area filled in with a white background by default, and you'll be able to make a selection there. You also notice that there's a on value changed event here. So when the user selects a different option, you could have invoked some methods down here on different game objects. So this could be really useful when you want to give the user a series of options and basically let them choose one out of many. Input field is kind of similar to text in the The import field box is going to allow the player to basically enter in some text here. Whatever the purpose for that is a really common example, would be if you need to get the player name or a safe I own name, have them enter that in here. And then maybe you'd have bought in on the side so that you could submit that. And then it would take the value inside of the import field, Of course, have to reference these in script, but it would take the value, and you could save it where you could start a new game. With that value, you'll notice that there's some placeholder text in there. But as soon as the player starts typing in the box, that text goes away and then the real text would start being entered. So another cool component that's a little bit more complicated is the scroll view you can notice in the scroll view. I have two pieces of content here, which is actually the same two images from over here. But you'll notice that this girl view I've said it's with and height to not be big enough to actually fit off those. But yet it has both of those inside of there, and you'll notice that this vertical scroll bar updates to reflect that you can scroll up or down. Of course, when you hit play and actually tried the game out Ah, there's also the option of having a horizontal scroll bar. You can enable or disable these with these checked boxes over here. So the general idea of this girl view is, if you want to add content, you would go to school view, view port content, and, uh, I think it's better practice actually put it as a child object of the content. And then these images become a child of that. So now if we hit play, which would do in a second here, will be able to scroll up or down and v the different objects that are contained in there. No matter how much stuff we put in there will be able to scroll through all of it as long as the, um, corresponding scroll bars enabled and still there as thes child game objects you can see scope are horizontal on a scroll bar physical. You can, of course, change everything. So if you don't like the white scroll here or the background for that, that's all changeable. You just change the image of the color for it. So let's go ahead and hit play and just kind of try out some of these components over here . Okay, so just to demonstrate, you can see the text element. It's not interactive. Well, with by default, you can click on all day, but it doesn't do anything same with images, but images are actually attached is part of the component for a button, so buttons actually have a little you. I image here, and you can, of course, change the button to be something like the Unity logo if you choose, but you can click on the button all day. It won't do anything until you're actually added on click event here, but you can see that you can interact with it so the taco you can interact with that. Of course it's on off, so it's either true or false, and you can take that Boolean value and use it in your script. The drop down menus you can see it gives you a little check box for the selected option, and we can go down to different options here. The input box. You click on it, a press on it, depending on what device you're on, and you can import the text. If you're on Android or IOS, of course, it would present you with the keyboard, so it's just type something in. And of course, you probably want to use this in combination with the button or something so they can submit. Really, All of the's would work really well with the buttons so that you get these import fields filled out by the player and then you hit the button, which might say you're on a safe script and then off this information gets saved somewhere in your game. City can use it and you can see with E scroll Bar. Over here, we can scroll to see the two images. If we had a images that were going wide horizontally rather than tall vertically, you would also see a horizontal scroll bar here, which would allow you to scroll left and right as well. So that's all there is to the default you. I components, as you can see there individually. Pretty simple, for the most part, but where it becomes powerful is when you start combining them and you build out your own menus using combinations like import text, drop downs and toggles, and then you complete it with a button. But maybe you also throw some images on the side to give your menu a little bit of ah, nicer look. So that's gonna be it for all of the default components. Inside of unity, I've been Chris. Thanks for watching. And also you guys in my future unity content. 5. MonoBehaviours and Unity Lifecycle Hooks (Update, Fixed Update, LateUpdate, Start, Awake): Hello, everybody, Chris here. And in this tutorial, we're going to be covering mono behavior scripts. They'll be introducing you to a few simple concepts of mono behaviors and will be creating a simple script that we contest out by attaching it to this robot game object. I have gone ahead and created. You can see that this robot has a transform where John came up, six to, of course, and a Sprite render, but nothing else besides that. So if I was to go ahead and hit play, absolutely nothing would happen. Even if I was to remove the tiles that exist under it, it wouldn't be affected by gravity. So our game object is about as simple as we can make it while still displaying it right now . So if we want to make it so, the our robot character can do something inside of the game while the game runs. We're going to need a model behaviour script for that. So to add a new model behavior script to our project, we can add component and type in the name that we want to give our mono behavior script. I could call it change color and by doing this. It will create a new C sharp script called Change Color by default the SOCO and the root folder off our project. I recommend trying to organize things a little bit and putting it in some kind of scripts folder like, So just because as your game grows, there's gonna be a lot of assets. So you kind of want to try to manage things a little better, and I definitely need to clean this up. So, uh, let's just delete that, Okay? In any case, this script exists inside of our project now, and it is attached to the robot. But it doesn't currently do anything, though. In orderto added it, we need to go over here to the bite and at its script. So edit script is going to open that file up in our code editor of choice, and we can check what code editor were using with unity by going upto adit preferences and then external tools. You can see here I'm using Visual Studio 2017. Visual studio code is also an option, and I believe unity also has mono developed. I don't know if that's still standard or not, and unity used to at least have mono developed. I don't know if that's still around, but you can use whichever editor you want. I prefer to go with Visual Studio 2017 so I'm gonna go over to the change color component inside of our robot inspector, and I'm gonna edit this script. So now that I have visual studio opened, we can see what's inside the script file currently. So you can see here it's by default declared as a public class change color, which is the name of our script, and this class extends the mono behavior class. You can see if we every over model behavior says it's the base class from which every unity script divides and that what that means is that basically, if you want anything to occur inside of your game, it's going to need to come, at least at some level. From a mono behavior script. You can create glasses that don't inherit from model behavior, but you're going to need a model behavior in order to execute anything. And the reason for this is that there are certain life cycle events that exist within unity that you need scripts, model behavior, scripts in order to hook into. So what will occur inside of unity is that the game engine will be running through certain cycles end on every frame. It'll go through all of the's methods, and any script that uses model behavior will execute their methods at those points in time . So, for instance, update is a method you can implement. And what that will do is that once per frame, whatever is inside of here is going to be caught. So if you're game run 60 frames per second, it's going to be called 60 times in a second is also avoid Fixed Update, which operates like update except it only is called a set number of times per frame. I'm not exactly sure how maney that is, but the differences update can run as many times as your computer can handle. But fixed update will be more of a consistent number, like 30 year, 60 times in a second. Usually it's recommended if you do any kind of physics calculation that you do it under fixed update instead of update. So that's the main thing to keep in mind. They used fix update. If you're dealing with physics or rigid bodies. There's also late update whenever you call late update, it's guaranteed to happen after update. So if you're waiting for some value to be obtained inside off one of your model behavior update methods, you can call that within update. And then you can be assured that when the update is called, everything that needs to happen an update has already happened. There's also awake, which will happen the moment that this script exists in the scene, whether or not the game object is created and then void Start will happen whenever you game object is set to active and then void start will happen the first time that the script is set to be active. So just like you can enable or disable a game object, you can also enable or disable scripts inside of the editor. You can see here this little check box if I was to have this unchecked, but then during the game, somehow I enabled this Boolean value. Then, at that point in time, the start method would be called. So there's these different life cycle events you can kind of hook into by implementing these methods, and by doing that, we can achieve most of what we need to inside of unity 6. Basic C# - Random Color Changing Script: So for this particular script change color is going to randomly assign a color to the Sprite render. What this means is that on every update fixed update to make sure it doesn't become too ridiculous. So what this means is on every update or fixed update, we can just get reference to the Sprite renderers, take the color of it and set it to a randomly assigned RGB color. In order to create such a script, we're only gonna need private void awake and five avoid update. If you care about exactly how many times it gets called per frame, you could also do fixed update. By the way, if you're wondering how many times fixed update actually will call per second, it's depending on what you have sat in your game. If you're wondering about how many times fixed update gets called or how you can change the amount of times fixed update gets called, you can go to the edit menu inside of the Unity editor, go up to project settings and then time and you can see fixed time step here. So this is set to 0.2 seconds, which means 50 times per second, whatever is in fixed update would get caught. So if you want to double that and you want this to run 100 times a second, you could just cut the time step and half, so this would be 100 times because 100 times 0.1 equals one. Or you could also reduce it to something like 7.5 where it would get caught 20 times a second. But so that means that the default is in fact, 50 times per second or fixed update the for this method. I guess we're just used the update method, which means it will get called as many times as frames happen inside of our unit project. But in order to change the color, we need to first get reference to the Sprite render So you can see on this robot game object. We have a strike vendor attached here, but the script doesn't know anything about that. So in order to get reference to that, the common way is going to be to first declare a sprite render variable, so sprite render and we can call this strike Render now whether you said it public or not here is gonna largely depend on if you want this to be sat inside of the unity editor because any ah, any public variables that you said inside of amount of behavior script is going to be serialized to the unity editor And to show up here. And if we set these variables to public, they automatically show up as soon as we saved the script. So if we wait here for a second, it should pop up with a field where we can actually set reference to the Sprite render. You can see that here right now. So one way to get reference to this bright render, of course, is to make this variable public and drag it in for right now. We're just leave that as our option, keeping it really simple here. So we're using the robots, right? Render an order to change its value. And this script If you're wondering why this value is black here, well, it's because, uh, this robot has a prefab object in our project, and this value actually is different from what's ever in the prefab. So if I check the prefab, you can see that's not even a script here for the color change. If we want this script and this right render to exist on the prefab, basically where Whenever we copy this robot to the scene, we can just go ahead and hit apply up here. So that basically takes this change and makes it permanent across all robots that don't have their own over it and values. Since we've set this right render inside of the unity editor, we simply need to make sure that that Sprite renderers still exists. And then we can reference the color and change it on every frame. So we need to make sure the sprite render is set. So if Sprite render does not equal no, then we know it has been set. So it's been set, and now we can do Sprite renderers dot color is going to equal a new value and this new value want to set it in several parts. They don't want this code to all go on one line because that'll be hard to read. So we will do color, new color, and that's gonna be equal to a new color instance. So this new color that we're creating it's gonna need three variables or you could also set for the 4th 1 would be Alfa. But we don't actually care about Alfa right now. If every call weaken set this as a value between zero and 11 where would have full value for that color and zero where there would not be any of that color rattle. And the colors are red, green, blue I believe as well Do we just need to get three random value so we can actually call the C sharp standard library of random dot value, which, you can see gives us value between zero and one point. Oh, okay. And, uh, that's actually a property reference, so we don't need to have the parentheses there. I think this works. I'm actually not 100% sure if this is going to return, um, the same random value. Our federal returned three different man in value. So we'll have to test that and see if that works. So Sprite render a dark color is gonna be equal to the new color. Pretty simple here, And that's going to be it for the script. Um, now, just to point out one other good way of getting reference to the Sprite render. If you don't want it to be manually set by the user, what you could do instead would be to dio Sprite. Renderers equals get component Sprite render. And what this means is that when the script awakes and the game when the game object exists and the script is attached to it, it's going to automatically find the sprite render component on the game object. And it's going to set this bright render variable equal to that. So by doing that, we could actually just change this to Private and the editor. The game designer wouldn't even need to set this right. Render. Now you would want to make sure that this bright render actually exists on your game object so you could do one of these require component Sprite render or a type of Sprite render. And by doing this when you actually attached the change color script to the game object, it's going to automatically add a sprite. Render to that game object if it doesn't already exist. By doing that, it's a lot harder for someone designing your game object to forget about adding the strike renderers when they add this change color script. This, by the way, if you don't know is called a attributes. And there are a lot of attributes in unity which you can get useful functionality out off, um, in ways like this with require component. So this script should be pretty crazy. And because I made the variable private, you should see it disappeared from the inspectors. So whoever is working in the inspector doesn't need to worry any more about this because it will automatically get reference to the sprite render. Now, if you have multiple streit renderers on your object, then obviously you probably want toe. Specify exactly which one you want. And in that case you want might want to make it public again s so that you don't accidentally grab the wrong sprite vendor. Either that or you could get get components and store all of this bright renderers inside of your code file. But that's getting a little too involved for right now. So let's actually just go test this crazy script. Um, So what should happen is that on every frame, the color changes to something completely wild. So let's give this a shot. Okay. Awesome. So we now have a seizure inducing robot that is changing color on every frame on. And that was all done by just getting reference to the Sprite render. Attaching our change color script and making it run on every single frame, Penn reminds me of TheStreet are effect inside of Mario. You might actually want to slow this down a bet, too. 7. Random Color Change on Timer Tracking deltaTime in Script: So if you want to slow this down a bit, one thing you could do is get reference to time dot doubt to time, which is the amount of time that has occurred since the last frame update. And then you add that time Teoh a timer variable, and if that time are variable has been passed. Then you can change the color. Let's go ahead and do that in our color change script, so we're gonna create a very bold called public float. Time to change, and this variable will have a default value of 0.1 F, which means 0.1 seconds. Represented as a float, Um, and because it's public, anyone in the inspector can change this. So if they want to change how often the change color occurs, all they need to do is go into the inspector here and that vary but will show up as soon is our script has compiled. Now we're also going to need to keep track of how much time has occurred since the last change, so we can do a private float time since changed. This, of course, is going to default to zero, and we're making it private because this is an internal reference. Very. But we don't want anything else. Teoh be able to change this or to mess with it. We only want this update method Teoh handle this time since change variable. So what we can do out here is add the Dow to time to the time since change, so time since changed plus equals time dot doubt to time. So now every time update is run, which is many times per second. This is gonna be incremental with however much time has occurred since the last update method. Now what we could do with that is we can see if the time since change is greater than or equal to time to change. And if so, then we can change the color. And if we change the color than we want to reset the time since change, it will make that zero. And this is the basis of how you can do simple time based effects inside of unity, whether that's determining the amount of time between a transition where you fade to black and load into another screen or in this case to randomly change its color. So let's go into the unity editor here and wait for this variable to pop up. By the way, if you are working in unity and you ever see vet text down here, that's the air messages that are being given to you by unity as it tries to compile scripts , you can check your air messages and find their spot in code by going over to the council, which it's almost always at the bottom of your screen. And that would be one reason why variables like this may not refresh because your scripts have to properly compile before they were actually update and re serialize all their variables inside of the Unity editor. But if everything goes well, then you should see the time to change variable. So this is set to 0.1. That's it play, and it should occur 10 times per second, so you can probably guess estimate that that's occurring about 10 times a second. But let's let's change the value here, which we can do by the way while the game is running. But if we change it while the game is running, it will permanently change. Only until we stop the game we can change this value to, say 0.2 and look at that. It slows down to half the speed. It's occurring five times a second. And let's change it to one just so that we can really see that it is in fact, running once per second. And then if we want to make it something ridiculous again, we can go back to 0.1 or is there is. There is a reserve one, but obviously it can only run so many times per second, and you can only see so many frames per second with human eyes. If your values ridiculous like this, then it will only update as many times as you have frames per second because your game just won't be able to handle more updates than that. So let's stop the game and you can see the value goes back to how we had it set in the editor. So if you just want to test out what value would look like inside of your game, what's running? Feel free to change it while it's running, and you won't have to worry about permanently updating it inside of the editor. So hopefully that gives you a good instruction on how you can implement time based functions inside of a model behavior script inside of unity and a good overview of how mono behaviors work in some of the unity life cycle events that you can hook into. So that's gonna be it for this tutorial. I have been Chris, thanks for watching, and I'll see you guys in my future unity videos. 8. Introduction to Scriptable Objects: Hello, everybody. Christer. And in this video, we're gonna be talking about script herbal objects inside of unity. So right here I have an instance of a script herbal object inside of my Assets folder. So you might notice that it over the years sharing some similarities to a prefab and that we can store it with all of its values inside of our assets for folder and then, like a prefab object, were able to reference the script Herbal object from other scripts. Model behaviors usually which would actually take these values or take the functionality of descriptive will object and do something with it. So you can see here I've created a script herbal object, God default settings. So over on the right, you can see it's got a Boolean value for whether the game has loaded or not a integer for the numbers of a number of times. It's been moated and keeping track of something like that in a script. Herbal object is not a good idea, and I'll show you why, in a bit the name of the first scene that we might load into the game when the player hits New Game or whatever the amount of starting money and the amount of starting health. If we actually take a look at the script herbal object, we can go out in here. It's an instance of a game settings. But the idea behind that particular one is that I would use it as a default settings in a game manager class, which could be a single 10 which could be a single 10 or some other script you have in your project. So things to note about script herbal objects versus model behaviors. For one thing, you do not attach them to a game object directly there, not a component, and they don't run their own functionality. So you're not gonna have something like public void update on a script herbal object that you would have in a mono behavior. So no, here, the script. Herbal objects, although that generally used for storing data inside of your project, they can still have methods in them because they're still a class, of course. So if you wanted to have something like public void, multiply starting health and then you could do like no, no, starting health times equals five. For some reason, I mean just giving an example here. You can have that. But the thing is because the script of object isn't its own model behavior. It's not gonna be executing any of these functions on its own. So generally what you need to dio is that you would have a model behavior doing. It's on update cycles as the game runs. And then it might do something on a script herbal object or call one of the script Herbal Objects Methods. So instead of a mono behavior, you would have the update method reference. Whatever script herbal object is attached to that model behavior Ah, in your hierarchy or you prefab. And then maybe you call the multiply. Starting Health meant that. So it be like the name of the file dot multiply starting health. Now what? We're on the subject. I'd like to point out that these manager classes I've been creating are actually script herbal objects in themselves, and that's why you see, appear at the top. Create asset menu game manager systems game manager, just like in this example script herbal object, a defense creditable object that is, we have create assets menu, the name of the class and then how you wanted to show up in the menus. So it's under the settings dropped down and then game settings. The differences with this yes, Singleton Library, which is available on the Unity Assets Store. There's actually a parent manager class which pulls in all of the script herbal objects and actually calls their functionality. So really so. Although this manager classes a script herbal object, it's being called by a Singleton update er, which, actually instead, she It's a single model behavior, which takes all of these Singleton script herbal objects and actually calls their functionality inside of that model behavior. Okay, so why would you actually use descriptive ble object in the first place? Well, there's a few advantages. First off, if you've ever worked inside with the hierarchy inside of Unity, looking at all these pre fabs the game objects, you may have occasionally notice that things sometimes go missing and you might lose references to certain data. For instance, when you delete a script from your project, then it might show up here or missing script. And all of this stuff that was tied to that script is kind of lost because that scripts no longer in the project. But if you have a script herbal object, this is actually an asset in your project. So this is going to stay there until you delete it. So this default settings asset file is going to contain this data until you delete this from the project. So you could attach this to a model behavior, and that model behavior script might lose reference to this. But it still exists in the project, and it's still gonna contain all of the's same settings inside of here, so it can be a decent way to store certain information if you don't want to lose it later on. Now, another cool thing about it and I'll show you an example of this is that you can reference the same object from different model behavior scripts so you can have one default settings object, and it can be referenced from multiple scripts and multiple objects throughout your project . So, for instance, the Game Manager, which is another script herbal object, as I mentioned before, has a reference to this game settings script of object, the default settings. So if I double click that you can see it pulls us over to the default settings instance of game settings, which contains all of this information. So by having that object set here, we basically have all of the information inside of that object ready to reference inside of game Manager. You also be able to notice if you click over here on the right to get thesis election. You can see all of the asset files, which are specifically instances of this game settings here. So it's pretty easy to pick one out from the project. And you can, of course, reference it from scripts that already exist inside of your scene or another pre family so you can see here default settings. Here is a field that takes a game settings, and I chose the Default Settings Asset File to be the instance of that. So multiple objects referencing the script herbal object for different reasons. So now we can talk about why saving values to rescript herbal object at runtime is not a good idea. The reason for that is that values in descript herbal object only permanently safe. When you're within the unity editor, you can see here that the game manager, when it's initialized method is called it sets came loaded to true and it sets times loaded plus plus, which means add one to it and then over here. And this is game loaded text script, which is purely just for testing here, Um, it will output the base text message, whether it's loaded or not, true or false, and then the number of times loaded. So in theory, what you would expect to happen would be the every time the game loads. Basically, every time a hit play increments by one, and that text should show a new number. So start at one to go to two, then three, then so on. And that a work in the editor. So if we're hitting, play in the editor like Will do right now, it will work that way. You can see here seem noted. True one. Okay, great. Now let's hit it again. And then we have seen loaded. True to If we check the script, herbal object will see that those values have been changed, as we would expect, so game loaded is checked times loaded too, right on Beacon it one more time just to prove that it does work within the editor. But as soon as we build the game and were no longer working in the unity editor. But actually the execute herbal file for the game. That functionality no longer works. So why I've already built the game? It was just build it to, you know, prove it one more time that I'm not pulling your leg or anything. So I felt the game one more time. Was that the resolution here to what I actually want for the project, which is 6 40 before he actually expressed 36 40 but 3 60 We'll fix that later. Um, so let's go ahead and hit. Play here and it'll give us this scene voted true. You know what actually happened? Because we change the value. And the editor it actually saved to the execute herbal build with that value. But I will show you without a shadow of a doubt If we run this one more time, it's going to show for so it seemed noted for And we can run it one more time. Just Teoh double proof. Okay, so you have seen loaded for But so the value only changes inside of the editor. So for those reasons, you can't really rely on script herbal objects to be a good way to say, save data permanently and rather for something like that, you would want to write Teoh XML file or binary through a serial Isar. But what script herbal objects would be good for is something like the default settings that should load with your game. Or maybe you create a folder with all of the items that might exist in your game off the swords, potions, whatever. And then the data that's stored in that you can reference that pull that in for other classes, other manager scripts, other player objects or in PCs. But you should not change the values and the script herbal object simply because it's not state ful. And those values are going to reset to whatever it was that build time. So that's going to be it for this primer to script herbal objects inside of unity and future videos, I'll be showing you guys more about how to write them properly and what you can do with it on a more serious scale. So that's going to get for this video. I've been Chris, thanks for watching and also you guys in my future unity content 9. Making Items in Scriptable Object Inventory System: Hello, everybody. Chris here and in this video wanted to give you guys a concrete idea you can use for script herbal objects inside of a unity game. So you'll see here in this folder, I've created four instances of a script herbal objects. So these are all saved us dot asset files within our game project. And each of these files store certain information. You can see that you can add it inside of the inspector quite easily. Just like a model be script. The difference is that these asset files created from descriptive ble objects script don't get attached to amount of behaviour directly these air independent files that will exist inside of your game object, and they can be pulled into mono be here. So you can basically set these objects as a field value. Um, which, um, we can kind of demonstrate that right here So you can see here. This shop script would actually be able to take a shop script, herbal object asset file. But that's for the next video. Um, so let's go back over here to game items. So the idea here is that you can actually create a big list of things that exist inside of your game or data to use inside of you get without having, let's say, like a my SQL database. So if you need something a little bit more lightweight than that, you can just come in here and do something like create items game item and create a new copy of the script. Herbal objects that by doing that, you can just have a big folder with a whole bunch of script herbal objects, and they can represent all the items that exist inside of you. Get inventories, shops and stuff you might find in treasure Chest a few making an RPG. Let's take a look at how this script actually looks on this case. It's pretty simple because we don't generally want Teoh right methods inside of these script herbal object classes. You can definitely do that, and sometimes it makes sense. But at a base level, they were really intended for being able to store certain values inside of your game project to use inside of a game. So we extend script herbal objects so public class name of your script. Herbal object extends script, herbal object, and then here we just have the data, which I want to store in that script Herbal Object, which we would obviously take in use in another mono behavior script somewhere else. Now the magic of script Herbal object happens when you great away for it to be added to your game project as an asset. So the easiest way to do that is to use the Create Asset Menu Attributes, which takes a fi oh, name the default name for the file itself and the menu. Name the path to actually basically run the command to create the script of objects so you can see items slash game item. And if we go over here to the project folder Weaken, do create items, slash game item. And just like that, we've created the script. Herbal Object. We can drag this into a model behavior script. We can edit the values within that game object, which will not change in us. We manually do that inside of the editor or while the game is running inside of the editor . So it's not a good idea to usually change the values of our script. Herbal objects here because I mean change it when the game is running because if it's in the editor, it will save those values to the actual asset files in our game project. But if it's ah built game, it won't save those values. So you get a lot of inconsistency there, and you don't want to actually overwrite this data like accidentally changing the value permanently within the game when you only meant it to be sometime after the game has started in a specific file rather than for the entire game project as a whole. So generally I try not to set these values outside of the editor. You can create script herbal objects. The fields don't necessarily need to be serialize herbal. And we can take these game items and create an inventory system or a shop system by just referencing thes files to create basically a list of which game items should exist inside of the inventory of a shop or player. Adding copies of this data to those shop inventories of player inventories and we'll be talking about that more in the next few videos. So I'm gonna leave this one here. I've been Chris, thanks for watching in us. You guys in my next unity video 10. Referencing Scriptable Object Assets and Nesting Scriptable Objects: Hello, everybody. Chris Here in in this video, I wanted to talk a little bit about referencing script, herbal objects within other script, herbal objects making it nested and also using script herbal objects in your mental behaviour scripts. So first off, let's take a look at the script here, which is gonna be development in the next video shop event, which takes a reference to a shop script. Herbal object. You know it's a script herbal object because it always have the symbol. Over here. You can see that you can select this from the drop down, and if we take a look at the actual script very briefly here, it's the shop Ament. All you need to do to set a script Herbal Object is to declare an instance of that class object, and, as long as we have it set to public, will be able to choose that script herbal object from our game project. So it's really easy to take this asset file data, which we have saved in our project as a physical file and reference it within our other scripts, model behaviors or other script herbal objects. So an instance of where would be a script herbal object referencing other script herbal objects. Here is the shop itself. So the shop has a shop inventory, which, as you can see, has a list of thes shop items and the shop items have references to the actual game objects that we were talking about in the last video. So this cloud exists as a game item inside of our game. We might use it in a bunch of different places, but this is one place where we actually references it as a sellable item inside of our shock eso we could do the same thing with the fireball item, the servant item or any other items we decide to create here just by going right click create items, game item. And now this would be another reference, a ballgame item within our project. So by doing this kind of thing, it becomes really easy to have manageable data for basically a list of things that possibly enemy templates or item templates within your game into reference that from other scripts, and as long as these files remain intact inside of your game project, you don't go ahead deleting them or anything this that I should stay there properly. Um, now, one thing I do want to re emphasize, though, is it's not a good idea to go ahead and change the values in here while the games actually running. Because they'll be an inconsistency between the editor, where values that change in the game while the editors running will actually be safe to the asset file directly. But when the game is built and exported, those same changes won't be reflected in these asset files because it's already been built into a game. So probably stay away from that. But script of objects become a really good tool for having data you can use when the game loads, um, to start formulating things such as a shop inventory or the details of a enemy that you spawn on screen. So we'll be getting into that more in the next video where we start creating the actual shop, you I referencing the shop and the game items that exist inside here. Um, in order to create a decent shop experience, we can sell items to the player and we actually have an inventory which will reference thes same game objects, game items or instances of the game items that the player can use throughout his adventures . So that's gonna be it for this video, just giving you guys a little bit more information about script herbal objects in their applications. I think Chris and I will see you guys in my next unity video. 11. Scriptable Object Shop Inventory and Showing Items to Players: Hello, everybody. Chris here and in this video, I'm gonna be showing you how we can take script herbal objects and use them to populate a shops inventory and show that toothy player inside of EU I now I had already recorded this video there according to come out quite so well, eso the scripts already written, but I'm gonna go ahead and talk through them as best as I can. Sorry about that. For you losing the original footage. So to get started here we have this chest object. Ignore the fact that it's a chest, but what it has attached to it is the shop event script. So the shop event script has reference to a script of object called the shop which basically contains every double click on it, a list of the shop inventory. So all of the items that should exist inside of it and the starting amount for their shop items it also contains a shop slot. Because we're gonna copy this data over to the shop. You I as we create it and the shop slot is going to be the game object where we actually create that object on screen. So that's going to take the game item data the icon, the value in the display name and show that to the player as a shop sought could be a better name, but you'll see what I mean when we actually go ahead and hit play. So the shop event script is simply going to pop open the shop. You, I and Stan. She ate this. Let's actually just take a look at the script here. So shop you your sari Shop event here. If a shop you I prefab has not been created hasn't been opened. Its going Teoh insane. She ate one of those on the canvas that's gonna get reference to the shop you I component. That's a script that's actually attached to the game object. And it's gonna open the shop from that script, copying over the data from the shop script Herbal object to the shop itself. Um, so let's go ahead and show that happening on screen, and they'll be more magic that you'll see immediately that will have to talk about so hitting play here and do whenever it decides to load. Okay, there we go. So on the canvass, the shop you I has been created. And this shop you I has a grid layout where the shops lots have been created onto. So you can see here it takes the shop data, copies it in here and then the shops. Lots are used inside of the shop. You I script, um, and the shops lots. Of course, you can click on the buy button. They currently do nothing, which is going to hopefully be our next video, actually selling the item to the player directly. But you can see that it has the price set. It has the title set. And as the icon the image set, this is actually a sprite being set onto an image. So the shop you I script over here it gets a few values from the Inspector, which is thes shop passed and through the shop event. Thea Advantage of doing this is we only need to create the shop. You I prefab once, but we can copy any shop, script, herbal object into those instances of the shop You I that we want to basically one shop You Aiken display any shop we have in the game, which is really handy. And then it has the the panel over here, the grid layout group, basically the spot where we want to put all these shops slots onto. And then the shop slot prefab or a shop item prefab, which is what keeps getting cloned here to display our data. So let's go take a look at that script in a bit more detail. So So the shop you I script, as I mentioned before, has those stuff in. There also has the shop inventory is a private missed over here. So rather than modifying the shop script herbal Object, which, honestly, it should probably be renamed a bit like shop template. Let's do that now. Actually, I'll forget about it otherwise so let's rename this Teoh shop template so that it can be referenced everywhere more properly. Because we're copying this data. We're not trying to add it. So let's see an open shop, which is being called from shop event. The shop inventory is being copied over from the shop template. We'll also renamed that here Shop Template is being copied over it into the shop inventory . And, as you know from earlier the shop items which there's a list of the shop inventory contains a shop slot. The reason for that is we want to associate the game object with the game item itself. So when we display a game object on screen that maybe has the image from that game item data, we also have a link. We have a link between the data and what's shown to the player, which makes it easier to add it later on. If we ever need to do anything like subtract one item from the inventory, which will probably do in the next video, Um, but then, besides that we have this populate shop item's function method, which is really important. So what it will do is when the shop opens for every item that exists inside of the shop inventory which were taking from the shop template. Basically every item we wanna have in the shop we create a new game object here. And Stan, she ate we instead. She ate that on top of the shop layout. The shop Leo is a Gridley out group, so it takes care of organizing its display on screen grid. Leo automatically does that, and after we've created the prefab, it should have a shop slot attached to it. This is another simple script which contains references to the title price texts and the purchase button. Um, and we take the data from the copied over shop items and we update the shops lots with that same self. So whatever the display name is for the item that we've set in the script Herbal Object, we put that on the title here. The text of the title. Same for the text of the Christ. We update the value from the script Herbal Object. We also take the icon from descriptive object and use that to show for the buttons, image display and Leslie. We take this object we've created and we associate that inside of the shop inventory. So that's where this shop slot comes into play, which will allow us to link all this data together later on and make it easier to you at it . So the last thing we need to talk about year is thes shop slot, which simply contains references to the title price texts and the purchase bottom. And that is manually set in the editor for the prefab. So I can show that as well. Here we have the shops slot So the shops thought, as you can see, is a game object prefab, which has the script where we set the references. And then we have the name tax, that purchase item button and the price text. The reason for the script is just making sure that everything is linked up properly and we can reference those fields in the shop. You ice script. Do you properly update them? So one thing I want to point out is that if you ever change the class name of a script herbal object, you also need to change the script Name of descriptive object class. So you see here is now shop template dot c shot. The script name has to match up with the shop template, Um, or else your asset files are going to kind of be a little bit screwy and lose their references. But your asset files are so they're so once you update the sea shock file name, the data will still be there. Don't worry too much about that. Just know that you need to change both whenever you change one. Um, so now we can go ahead and take the shop which would call shop template now and we'll link it back up to the shop. You. I prefab so shop you I as a prefab is gonna take reference to the shop template. And now, if we go ahead and hit the play button issue of work, as it was doing before, and it is. So in the next video, we're going to be updating thes scripts with the ability to have a player inventory and to copy one of these items into the players inventory so that they can use it as they adventure throughout your games, whether that's a healing potion, a fireball or a servant, that they can spawn in the game and used to help them out with their questions. So that's gonna be it for this video. I hope you guys are learning a bit about script herbal objects, and I was So you guys in my next unity video 12. Aseprite vs Pyxel Edit Pixel Art Animation & Tile Tool Comparison: Hello, everybody, Christer. And in this video, I wanted to give you guys a comparison between aspirate and pick so at it to pixel art creation tools specifically designed for pixel art. You could, of course, you something like photo shop or gimp, and you'd be able to create pixel art. But because those programs aren't specifically designed for you, get a lot of weirdness when you're trying to do things like, let's say, rotate a few pixels 45 degrees or to place of one pixel square on your screen. So one thing I want to point out for you guys before we get into this video is that I am definitely more of a developer than a pixel artist. I am new to the whole creating pixel art thing, and though I think I am improving, I would not consider myself, like a professional artist or anything. So keeping that in mind, let's go ahead and get started with comparing the two programs and hopefully give you an idea of which one you should pick up, if not both of them. So in both of these programs were able to create multi frame animations quite easily. You can see that the different components of this animation are split into separate layers , which makes it easy if you want to do something like move this top pedal without moving the flour based down here at all. Or if you want Teoh add things to, let's say, the spot down below rather than messing with the whole pot but having that sit on top of it so layers of pretty much a given. But in addition to that, both programs they're gonna have onion skinning, which allows you to see the before and after frame and the ability to play back these animations while you're editing them so you can go between animations pretty much same in both of these programs. So over here you can see the pixel added version off this. If I wanted to make some changes, I could just draw them on, and you'd be able to see them appear here in the animation, basically as soon as I added it, or even while I'm considering making that change. So if I increase my brush size here and I was to have her over here, you can see in that play back window at all show at the pixel that I'm trying to add it. Of course, here there's also onion skinning. Same as with aspirin, right, and they are really good tools for being able to animate this pixel art. It's a lot easier to actually see what you're doing when you have that playback window and the ability to animate different components on separate layers. So that's all well and good. But those air where these two programs a really similar when it comes to animation, I would say where pixel at It Falls week here is that you can't really see the layers and their reference to the animation you're doing so easily, so you'll have these layers over here. But you won't have any indication about if there's something in that layer. With this little circle, you can't click on a layer in a frame of that layer and copy and paste that somewhere else . Just with control. C Control V. Unless you're going to basically go to that layer, find the frame, copy it like this and then drag it to where you want it to be in the next frame. Also, I feel that the labeling you can do up here in Aspen, right? Makes it a bit easier to organize your frames, your animations and to see exactly where you're working on three ability toe copy. Entire Rose airframes is also nice. Now how you can see where an animation starts and ends in pixel data is when you have those animations selected. You can see over here that there is this thin blue line s so that's where the animation would start. And over here in the bottom, right. We can see where the animation ends, but it gives you a bit less information about what's going on with those individual layers over here. And then having the labors over here is a little awkward. If you were going to do an animation on multiple layers, it's not that you can't do it. You totally can. It's just a little bit more awkward than the flow of asp right over. Now, a couple other things about aspirate that a good before we get to the advantages of picks. Audit. First off asteroid does have more tools for you to work with when it comes to creating picks, so art. So you have a contour tool over here and colleague on tool for creating various shapes. You have the jumble tool over here, which is pretty cool. If you want to create something like a gravel effect, you can take pixels and mix them up very easily. And the blue tool allows you to easily get some kind of anti A liest edges on your Pixar if that's something you want. So then there's also the Grady int tool over here, pixel at it only has paint bucket tool. So if you wanted to get effects, were basically have one color transition into another. That's something that you don't really have access to and pick so at it. So I could see this kind of thing being used for If you have, like a based background color that's just kind of blurred out, maybe something that looks a bit more like this, where you would have grass in the background and then above that, some kind of sky or missed So one other tool that's pretty useful inside of aspirated is shading, So if you have the pencil to a selected, you just change the ink from Simple Inc to shading, and then you can select colors over here And while you have these colors selected and it recognizes one of those colors inside of your artwork, you can see here the middle color is there. Left click will turn your color towards the left, basically making it a lighter shade and then right click will make it darker, so this would be really used for if you're doing something like freighting of rock and then you want to get a couple different shading colors really easily without having to you manually switch between them so you can easily make your colors lighter and darker. Now that said, although pick so that it doesn't have that, you could easily just select your colors manually and then going to go over here and draw them now. That said, although pick Side it doesn't have the shading tool, you can just kind of shade yourself. If you want to do it more manually by selecting the color, you want a shade left clicking, and then you go to the next color and putting that and it's not hard to do that and picks on it. So let's talk about where pixel at it is really strong, and to me, that would be tiling. So in asteroid, for whatever reason, you don't actually have the ability to take, let's say, 16 by 16 pixel square and turn that into a tile and then to tile from within aspirate, you can draw an tiled mode which you could do by going to views. Let Seaview tiled mode Thailand both access. And then, if you have, like 1 32 by 32 pixel Sprite, you'd be able to see how it tiles and you can still draw it like that. And yeah, that's all well and good if you only want to work on one tile. But if you want to see how multiple tiles can interact with each other, then picks out, it is definitely gonna be stronger here. So inside of Pixar, I can create a tile. And then now that I have in my tile base, I can just put it onto the map really easily and start placing my tiles, and you can also rotate them as you can see year. So you don't need to make four corners. You only really need to make one. Um, then we put the sites in, and just like that, we've tested our tile inside pick. So edit now to create the tile. Of course, you have to use this tile place or tool. So to use the title place you tool, we've gotta hit control click to create a new tile. And once you've done that, it appears down here below you can duplicate it, make modifications to it. What if you want to do? Earlier today I was working on this a bit, So this is basically kind of a prototyping of how one of my levels might look in the game and currently working on, and you would have a pretty tough time doing this kind of tiling if you were working out of aspirate. Now that's that. You could just get a tool like tiled, which is specifically about taking tile sets and creating your game maps. And then you can export that to programs like unity. So it's not like you couldn't just create your tiles inside of a sprite and do that. But having these features for tiles, it makes it a lot easier to test out your actual pixel art. If you're if you're trying to deal with tiling and see how it all kind of comes together before you actually put it in your game. So that basically summarizes most of the differences between the two programs, which do, I think is actually better. It's a really tough call. I think. I like asked Right when it comes to animation, and when it comes to things like making a character animation, I think I'm gonna be playing around with this tool more in terms of creating tiles. I definitely give the edge to pick so at it. So I suppose if you had to pick one of the two programs, it would depend on what your focus is. If you are trying to animate a bunch of characters, I feel it is easier to do that inside of aspirate. And if you're trying to test out tiles, I think you're gonna have a better time going ahead with pixel at it simply because when it comes to creating and using tiles, there's a few additional tools and their that it more specialized towards that. But you would be just fine if you used aspirin plus and other tools such as tiled, which is free to use. By the way, there's also been good to Doyle's on YouTube so far for creating tiles and aspirated, even if you want them to kind of tile them together and see how it goes, you can do all that in s right, so you'll be fine either way. And then, of course, when it comes to doing animation, the U I and aspirate feels a lot more user friendly for creating your animations in the program. Thanks to the timeline down at the bottom, it's very nice. So just to point out a couple more things that are pretty relevant pixel at it, I believe it's still in its beta. It's pretty much fully usable. I mean, you can see everything on screen, but it's still at 0.4 dot eight version wise. So maybe it's not quite as complete as aspirate asked. Right has been around for quite a while. It's a version one dot to 1.0.9 that said, I've actually been using picks at it longer than aspirate, which I picked up a few days ago. So, you know, maybe a little bit it's there, but hopefully, overall, I was able to give you guys a really good idea here. Of the two programs and the minor differences between them. So I think, Chris, thanks for watching. And I will see you guys in my future video content. 13. How to Import and Create Custom Color Palettes: Hello, everybody. Christer. And in this video, I wanted to show you guys how we can install extra color palettes to Aspe, right? So that you can use them on your picks are. So first off, I'm gonna go find a decent color palette on nine. So low spec dot com slash palette dash list is a really good resource for finding colors for Pixar. Okay, So, Don, bring your 32 colors. Looks pretty good. So we'll go ahead and download this palette file from here. Says you can see the site has special formats for photo shop and gimp, but inside of ASAP, right? We can actually just use PNG image one x here, which is going to give us a really tiny image file to download essentially what this is. This is just all the colors and a row. So resume in here. We can right click and save this image. So where we're gonna want to save this new color palette is going to be wherever we have asap right? Installed and then into the pallets folder. Don't for me. I have asked right on steam. So I want to go to see Dr Program files And then from the steam directory, we go to steam APS common ASAP, right Data and then into the pallets folder. So, yeah, if you have asap right and it's not purchased on steam, the location might be a little different. But we just saved the PNG image into this folder, and now we need to restart ASAP. Right? So I'm gonna close this out, and I'm going to re launch it from my computer. So brooding that up, we can start a new Sprite file very quickly. And let's go to presets over here in the top left to select a color palette. And we should see the Don bringer 32 over here so we can just select that, and then we can start editing with those colors. Now, if you want to customize your own palate, you can click on the edit color icon over here in the top left, which will unlock the palate. And then we can make changes to the colors by selecting the color. We want to change your different one. And let's just say we did this a bunch. Then we can go over here on the right and choose save palate and then we would save this in exactly the same location. So for me, that's going to be back in this steam folder steam APS common ASAP, right that. Ah, pallets. And just put it here with a new name so we can call this custom palette and just save it. And then the next time you load up ASAP, right, that custom palette should load up by default. So we can see custom pallet loaded right here. And that's pretty much all there is to adding custom color palettes and two ASAP, Right? So I think Chris, thanks for watching, and I will see you guys in my future content. 14. Best Way to Import 2D Sprites & Pixel Art: Hello, everybody. Chris here and in this video, I'm gonna be showing you how you can properly import to d Sprite our assets into your unity to the game project. So if we take a look here at thes little sprites I've dragged and dropped onto the scene. You can see a few problems with, um, one thing. If we zoom in a bit here, it may appear blurrier than it. Otherwise, it would look if we opened it up with the program, like Photoshopped may appear blurrier and unity by default. Another thing is that we drag in here and the scale might not be matching up, so you might have an object which is supposed to be as big or bigger than other characters . Or you may have designed your character so that it fits into a couple square units like Let's say you designed it at 32 pixels per unit, but it's not displaying at 32 pixels per unit. One other problem that may occur while you're trying to drag us right into the scene is that if you are using a sprite sheet, if you drag the image over here, it may appear on screen as every single spray inside of that image rather than one individual sprite. So all of these very common problems of blurry pixels, the object not matching its pixels per unit properly and having multiple sprites be dragged onto this thing can easily be rectified inside of the project photo. So if we click on a Sprite based our asset that we've put into our unity project, what you'll notice is that over on the inspector, we get a lot of modifiable properties that we can use to adjust how those sprites are rendered inside of unity. So the first thing you might notice up here is called Sprite mode. It's beautiful, set to single, and you only want it set to single if there is only one sprite inside of the image. So if you have an image like this where it's one of those Parana plant type things, or if you have a mushroom sprite that does not have any other sprites inside of the file, then leaving it as single is fine. But if we're working with something like a spreadsheet of four chests, we need to change this from single to multiple. However, in order to actually break this file into multiple sprites. We also need to go into the Sprite editor over here, so it will ask UN applied import settings. We can go ahead and hit yes, on that. And when the Sprite editor pops up, you notice all of this brights basically displayed on screen for you to slice the sprite she up into individual sprites that could be used within the unity editor. So to actually slice them up, there's a slice option off here at the top. Left automatic is one option you can sometimes use in order to get decent results. But if you know the exact grid size that you were working on doing grid by South sizer grid by cell count, I may work better in many cases. So I believe that these files have a 32 by 32 pixel grid size. So if I change the X and y pixel size value and then hit slice, we're going to get perfectly sliced grid items. For the record, this is why it's so important when you're making pixel art to keep things on the grid so that they can be sliced up properly on the spreadsheet. So once you have your four sprites individually sliced here, we can close that out. It will give you an applied import settings. We want to apply that because we want to confirm this life. And now the chest object that we've dragged into the scene is showing as one sprite. If we expand the spreadsheet now, we can dragon individual sprites, as we please did. That fixes one problem. The other here is that the sprites look blurry, which isn't good for us. Bright game. In order to rectify this, we can select multiple items to be efficient. So all of these items that we're working on right now, I select them by holding the control button down and you'll see under the advanced having the inspector filter mode by linear and compression mood, normal quality or a low resolution Sprite based game. I highly recommend you change, fail to murder two point, which is no filtering and then compression mode to normal quality when we hit. Apply now, what you'll notice is that the Streit's become much sharper, similar to this robot and the tiles underneath. It looks like it should, or it looks like we designed it to be inside of another program like photo shop again. So lastly, you can imagine that these little game objects or the sprites for the game objects were designed to be at least one square pick. But currently they're not rendering as one square, and that's because they were designed at 32 pixels per unit. But whenever you import sprites into unity, as you can see here, it defaults the pixels per unit to 100. So if you are designing your items or your characters or your game objects at 32 pixels per unit or any sprite sheet or sprite, you import into unity. Change it to the proper pixels per unit. So here I'm gonna set it to 32. Now we cannot apply. And now this object should appear with the right size, and I can drag it where I wanted to go, just like you did with filtering. If you know that all of your assets have a consistent pixels per unit size, you can grab everything in your assets photo. This time I will do ah, shift left click on the last file in order to select everything between the first and the like final, and we can change the pixels per unit to 32 hit apply to change them in Mass. And if I do the same thing with all the files in this folder, changing the filter mode to point and the compression quality to none, then we can get the right look for all the sprites. And when it comes to changing the Sprite mode from single to multiple and slicing up the files, you'll have to do that individually because each sprite she is going to need to be cut up differently in many cases. So just to be show here, I'll go into the Sprite editor after setting it to normal mode and will slice 32 pixels by 32 pixels. You can see that this actually takes up two squares. So one thing we could do if we want this to be suitable, as one object is we could actually change it. Teoh, with of 64 pixels by 32 pixels and now each of these mushrooms are one object, even though they take up two squares horizontally, and we can do the same thing with these mushrooms that are supposed to go on the wall. So said it to multiple Sprite editor apply Slice it up and then 30 pixels by 32 pixels because that's how these mushrooms were designed so we can apply it. And now we've taken care of the import settings for all of these are assets inside of this objects photo. So hopefully that gives you guys a really good idea of how you can import to D pixel art or sprites into your unity games and get them to display properly. I've been Chris, thanks for watching, and I was you guys in May. Future unity content. 15. Control Sprite Rendering Order (Which 2D Objects Show in Front): Hello, everybody. Chris here and in this video, I want to show you guys a quick and easy way. You can have sprites render in front or beyond each other through a simple calculation. So in this case I have this moveable dog character and this tree. And if the dog is in front of the tree, I want it to render in front of that tree. You can see that as the sprites overlap, the dog gets shown on front, but if I go behind the tree, then the tree will show in front. So that's a pretty cool effect you can get. And it's not too complicated in order to get, um, if I go, take a look at one of the inspectors for these game objects, you'll notice in the Sprite. Render that there is an order in layer that's set to something other than zero. So by changing the order and layer, we can change which one will show in front of the other. So you also notice as they move around, that order in mayor changes and that changing as I move in the Y direction is what allows three game to figure out which object should show in front. So over here I have the code for controlling that sorting order. So in my case, I have as a single 10 basically a game manager system. So this is always running, and it's only one of it. Um, now, if you want to implement this kind of thing, you can use the yes Singleton Package. But really, the only thing we really need to focus on here is that we get all of the strike renders and the scene in one way or another. Um, this way, coming in on on update. It's not very efficient because that means on every single frame, we have to go look through all the objects in the scene and find every single one that has a strike render that said it does work in any case, find a way of getting access to obvious bright renderers. And then, for each of the sprite renders, you have to change this sorting order to some kind of formula. So the important thing isn't exactly what's in this formula, but rather that it is consistent across all of your objects. So in this case, I'm taking the white position of the transform of every game object that has a sprite render, and I multiply that by negative 100 to get the sorting order. The reason why you multiplied by a negative number is so that if you're going down on your game and you get to a point where the position is actually under the negative units, so, like negative 0.9 that the order and layer is positive because positive numbers will show in front of negative numbers. And if you want the items that were lower, basically they have negative white positions to show in front of the ones that have positive white positions. Then you should make it a negative number. That's the important thing here. I've also seen people two times negative 10 but I like times negative 100 because it gives Mawr fine control over the order of the objects, basically, by multiplying it by 100 before you cast it to an integer here. Because the sorting order is an integer, you'll get more variety of numbers there, and slider moves will have a greater effect on this order. You could even do times 1000 if you really want, but anyway. Ah, you just run a calculation and you put that into the sorting order. And then whichever items have the highest sorting order value are going to show in front of other items for that layer. Beyond that, the only important thing is that all of these objects that you want to sort with each other should be on the same layer. So if you go over this sorting layer and you add sorting layer, you can create a delay, which all of these things they're gonna show on so you can see here I have one for objects , and I'm also playing around with a sorting layer for shadows and particles, which you might want to always show in front. Um, and in terms of these layers, the layer that is at the bottom of the list will always show on top of the other ones. So that's really all you have to do. You have to give it a sorting layer value through script, and you need to make sure that all of those objects are on the same layer. And then, by doing that, you can have an object go behind a tree. But then, at the same time, be able to go in front of it as well. So that's gonna be it for this video on controlling the vendor or sorting order inside of your unity games. I've been Chris. Thanks for watching. And also you guys in my future video content. 16. How to Create Shadows for 2D Game Sprite Images: Hello, everybody, Christer. And in this video I want to expand on my last video on Sprite vendor sorting order and talk about how to get shadows to work in a to D game for unity. So this method of doing shadows is basically where you have shatters baked into the scene as its own separate sprite. So this tree has a shadow. But this tree and the shadow down here, actually two separate objects, and the reason for that is that we want to be able to, let's say, have the tree show in the background, but the shadow to still fully effect this dog as it walks through. Basically, having the shadow and the tree on different sorting layers allows this to occur. Otherwise, you'd run into issues like the Shadow would not show if you were in front of it, like right here. So if we take a look at this game object, it's got shop event. But really, it's just the treat. You notice that there is a sprite render for the tree on den. As a child game object, I have a secondary sprite render that's rendering this shadow. So no here that this sorting layer for the shadow. Sprite is on the shadows layer, and you can call them whatever you want. If you want to add your own layers, you just click on sorting layer and then add sorting layer. Whatever is nearest to the bottom, we'll always show on top. So this player game object player game objects Sorry is on the objects layer, so the shadows will always show in front of it. And that's why if the dark walks through it, even if the dog's position is actually below the shadow, the shadow will still show on top of it. And it's partially transparent, of course. So it gives, Ah, nice shading effect on the dark, and you can also see that the tree itself is also on the objects layer, so that allows starting to happen for, like the dog to actually show behind the tree if it is at a higher white position. If you have any questions about getting Theo order in layer value set, just refer to my previous video. Okay, so this is what the actual image for the tree looks like, and I'm pulling these images off of open game. It's, um, there's a bunch of really quote trees, originally by Casper Nielsen. But there were some re colors done by William Thompson. This is the information Go look them up on open game are if you want to check these trees out because they really well done. In my opinion, on this right, we have the shadow down here and you can see that it's not being rendered inside of the game engine. It's actually baked into the Sprite itself, and then we have the tree over here. But currently it's all on the same layer. It's the same image. So what we want to do is you want to separate it into two separate images. So basically, we need to take all of the shadow area and move that into a different layer. So to do that, I'll use the magic wand tour over here in Photoshopped. The process would be very, very similar. If you happen to be using gimp or some other program at the moment s, I'm gonna have to turn this tolerance down to get a better selection. We don't want to grab any of those tree pixels. Um, maybe I'll even though whereas Lois one or zero Okay, So what we actually have to turn off here is anti alias ing. I've got about that. And now you can see that all of the pixels, which are specifically, uh, the shadow have been selected. But everything else has been left alone. So we can just control Z to grab that. And while we're on this new lay, we want everything to appear in the same spot so I can go up to the edit menu paste special and then paste in place. So it's now in the same spot. It was in the previous layer. And for these extra pixels, Aiken just kind of rough. Grab them with the lasso tool, and then I'll cut them again and do another paste in place. Okay, great. So now that's two separate layers. We want to merge them. So I'm gonna right click and marriage down. And now they're Shadow is all one layer. Great. Now you could make the case that, since we're dealing with two separate images now, actually makes some sense for the shadow layer to actually include some of that inner area because there would be shadows with the tree trunk is actually at up to you if you want to do this. But if you want to feel that in relatively simple here, we can just I dropped to get the color of the shadow Cynthia Pass ITI, which it believed that the shadow is 60% and to go ahead and feel that all in adjusting the shape a little bit as needed. So this is basically dependent on whether or not you want the shadow to hit the tree as well. So now as you can see by putting that shadow in because the shadow will always look on, be on top, it'll look something like this, and the tree will actually happen. A shadow as well. Now, now that the shadow has its own section over here, covering the tree, the tree itself can cast its own shadow on the tree trunk. That's something you're looking for then. Great. If not, then just don't worry about filling it in. Now we need Teoh export these as two separate images in to unity. So in photo shop, there's a function called layers to file sits under exports, so file export and layers to files on. By doing this, we can create two separate files for these two different layers. So I'm gonna export that to my unity game and I'll hit Run here. As you can see, it takes both the files and exports them. So beckon unity. We can see that these two files have been created. So because thes images both have two sprites on them, we need to change this bright mode to multiple. And I Let's stop the game for right now. Um, and also we need to change the pixels per unit to be consistent with the game and the sprite size, So I'm changing that to multiple on 32 and multiple on 32 for the shadow as well. So now we can just open. There's up in this bright editor and weaken slice them. I'll just do it automatic slice for right now. So that basically cuts around the edges of the Sprite and figures out what should be inside of it for both of them and are hit apply. No. One other thing I want to do here is to actually change the pivot point. And I think this is one of the things I was trying to find a better solution on but for right now, changing the pivot point. Well, basically determined for the rendering order. Where should it be? Calculating the order from. So if you have that kind of calculation, you game where you're taking the position of it. Ah, this will be basically way. The position is in terms of the Sprite. So at about 0.15 there and then 0.12 for this one. But of course, that's not directly related to this tutorial, so you don't necessarily have to do that. Okay, so I hit. Apply here, and we can go back to the shadows. So in the shadows spread editor are just automatic. Slice them, um and yeah, you know, it might make sense to cut away all of this extra white space and the final export. I think you can have that crop when you're exporting from Photoshopped as well. But for right now, we'll just leave it like that and worry about it later. So I'll apply that. And now we need to bring those items into the scene. So I'll just copy that prefab I had and for change the sprites on it so I would do this green tree over here. Oh, and the reason it's blurry, by the way, is because we have filter modes turned on for the sprites. So for both of these layers, we want to turn it to point filtering and no compression hit apply. And that'll make your sprites look a lot smoother. So obviously, because this is a difference bright image, the collider isn't gonna be perfectly right. But we don't need to worry about that for right now. Um, let's just focus on getting the shadows in there, so changing it to the second shadow, you can see that the position isn't quite right. So we want to align that. So I just do this like the most simple way possible, which is going to just be to layer them on top of each other. And now I think this shadow was supposed to be a bit darker. Uh, you know, for the sake of just having the order and go here, we can just stick with this for now, and, ah, worry about that later. So the important thing for this video is that the character can walk behind the tree but will be affected by the shadow in all cases. And you can see that because we have the sorting layers set to shadows for the shadow object, which is a child of the main tree. Um, and the tree itself has a sorting layer of objects. Objects, which is consistent with the player dog will be able to get the effect we're looking for. So let's go ahead and hit, play and test this out so the character walks behind the tree. But as soon as you go in front of the shadow, it's going to start showing on your character. And that applies whether you're behind the tree, whether you're in front of it and also if the players well below the shadow but just barely touching it in terms of the sprites. If the shadow was in ah, higher layer rather than a lower layer or in the objects layer than it clearly would not be affecting the dog, it would hide behind the dog. So you could actually make the case that the shadow could also be on the objects layer as well, because if you think about it, if the camera is coming from out here and kind of looking at the tree, but the player itself is between the tree, the tree shadow and the camera. Then you might actually not want that shadow to show in front of the dark when it is this close. Um, simply because the shadow might be cast on the opposite side of the dark, but not on this side that sexually facing the camera. So if you want that you can just change the showing layer over toe objects and what you can have is they setting a pivot position on the Sprite? Um, that this price of thes shadow you can kind of determine. At what point will the shadow start affecting the dark, or where will it not so kind of up to you on exactly how you want to implement that. But the general idea here to take away from this video is that your shadow and the tree or whatever objects you're working with should be separate images. You should bake the shadow as a separate sprite rather than having it render and real time rather than it might in many three D games. And you'll just have to keep in mind you're sorting layers in the order in layer as you figure out which objects should be showing in front of the camera and should the shadows actually show on the dark or not once again, if you want to take a quick look at that script I had in the other video, the main thing is that you just take all the sprite renderers and you give them a sorting order through a simple calculation. And the reason we times it by a negative number here is so that negative numbers which are closer the bottom of the screen, will actually render at in front of objects that are closer to the top of the screen. In other words, more in the background. Um, see, I just take a quick look at that code if you wanna implement that, and you might do this is a model behavior attaching it to every game object. But I have it as a singleton using yes, Singleton, which is, ah, package. You can get on the Unity Assets Store. But the general idea is just take out the vendors and give them a sorting order through your calculation, and you should be good to go there, So that's gonna be it for this video on how to get shadows to work when you have a game object that needs them, having them as separate objects and getting there, sorting orders to work properly. So I've been Chris, thanks for watching this video and I'll see you guys in my future unity content. 17. How to Setup Baked Lighting to Illuminate 2D Pixel Sprite Games: Hello, everybody. Christer. And in this video, I'm gonna be showing you guys how we can add lights to a two D pics of game inside of unity . So that's gonna be a few steps for this. First off, for all of the sprites which we want to receive lighting from the unity lights, we're going to need to change the material on their sprite render. Or if you're using tile maps for all of this floor and wall stuff, then you also need to change it for the time at Brender. So by default, the material set here is sprites default which does not receive lighting from any source. Is it only displace as you imported it. So what we need to do is create a new material. So this material I'm coming at Pixar diffuse. You can see that it is using the shader sprites slash diffuse. So we can just go ahead and recreate this real quick if you right, click and go to create and then down here for materials. Uh, we should be able to create any material and shader. We want to change this to sprites and then diffuse the last thing I'm going to do is check pixel snap because we are trying to do a pixel art game with pick so perfect art. So once you've done that, you can go ahead and assign this material to those spray renderers because I already have it. I'm just gonna delete that new one. I'm going to shift select these six grid tile map components so that I can change their material once. So where says material? I'm gonna select here and we're going to go down for pick so diffuse when you do that, you should notice that all of your tiamat objects pretty much get dark immediately. So now they need light and order for you to see it properly. So creating a light inside of unity is pretty easy. I can come down here to a game object or if you want to create an empty just right click, create empty. This is only apparent object to I know, organize off the lights. I'm going to right click it and at in light point like here. Now for me, it's showing it immediately for you, depending on the value of your grid or all the objects in your scene. You may need to change its position because, remember, even if you're building a to the unity game, objects still have a three D position and that with this light we can manipulate its range and intensity to get the setting. See where you want. So if we want less spread across our tile map grid, we can decrease the range here. If you want the intensity basically the amount of light to go up, you can take intensity, and you can ramp that straight up to whatever you think would be necessary. And, of course, you can manipulate the transform, so pretend this light was like a torch on the wall. Then you could kind of position the light right on that torch, and it would make a lot more sense. Now you'll see in mode that it's gonna be set to real time. And if you click on this drop down menu, mixed and baked are probably going to be disabled for you out of the box because we need to enable the setting for baked and mixed lighting so we can do that by going up to window rendering lighting settings, and now we want to scroll down here and there'll be a check box baked global illumination associated with mixed delighting. If you check that and you set the lighting mode to either shadow masks, attractive or indirect, amusing subtracted. Right now, I'm using subtracted right now this obviously different lighting modes and you can check on the website if you're really curious about that. But the reason we are changing it to baked lighting over here in Moz now is because real time lights are incredibly unnecessary for a two D Pixar game. We don't need it toe constantly do things like calculate shadows. So where we have mode, we can just change that debate, which is gonna make the performance on the light a lot better. It won't be taking up nearly as many system resource is, and with that, we can basically go ahead and test it out. Now, if you want game objects like, for instance, this door up here, do you also receive that material and thus receive the lighting? Then you got to change it for each object individually. So for the sprite render here, I'm gonna change the material as well, too. The pick so diffuse material that we've gone ahead and created. If you want more lights, you can easily do that. So I'm going to duplicate and move this light. Let's say over here maybe increased the range of this light a bit and decreased the intensity, moving a little bit more towards the center, and we can also duplicate that bottom light one more time. Position it over here and now I'll go ahead and test it out by hitting plate. So this character over here, my Bernice Dark it already has the material applied to, despite render so it can receive the lights as I move about in the scene. Um, so if I get really close to the light, you can see it becomes fully illuminated, and as I go further away, it gets dark. Same with everything else in this thing. Now, if you run into any issues with the rendering of your light, like if one of the lights happens to flicker or some reason when you kind of go off screen , what you can do is change the render mode from auto to important, which will force it to prioritize the rendering off that light. Um, just a quick fix. If you run into any flicker issues. But I think since I changed that to baked lighting, there's no issue there at all. That's pretty much it to adding some basic lights inside of a two d game for unity. Just make sure that any objects that you do, you want to receive light like this leaf over here. Um, you have to assign the material. Otherwise you're objects will display as if they were fully illuminated. And that may not be what you want unless you want it to be obviously visible, like this dark in the corner movie. That's gonna be it for this tutorial. Hope it helps you guys out. I've been Chris. Thanks for watching, and we'll see you guys in my future unity content. 18. Make a Simple 2D Tiled Background: Hello, everybody. Chris here and in this video, I'm gonna be showing you how we can add in a simple tiled background to a two D game inside of unity. So the idea here is that rather than changing the camera directly adding something like a three D skybox, what we actually want to do is to put an image inside of ours seen and make sure it's tiled . And also behind everything else in the scene, the tile map in any game, objects that might be interacting inside the same. So I'm gonna show you guys how to set this up step by step. First off, you want to right click on your scene and go to two D object and create a sprite. So it this right? What you're going to set? You can call it background if you want, So I just call it background to here, and then you need to pick a sprite to go in this box. So over here in my assets, I have a background. You can see that the strike mode is set to single pixels per unit is dependent on whatever tiled size you're using in your game pixels per unit is gonna be dependent on whatever tile size you're using for your game and mesh type should be set to full racked. If you don't have it set to full racked than when you tile it, it will give you a warning. So we should just set that to fall back to their No, assuming you're also doing a pixel based game filter mode. Should be point and compressions should be none. This will make it so that there's no anti alias ing or any kind of blur effects on the edges of your sprites when you put them in, and as a result, they will look exactly how they were created in an editor such as Asset Price. So with the proper settings on this BG Cave, P and G not weaken. Drag this into the Sprite field of this bright render, so that should give you something like this. You probably want to center it on 000 but now if we go to game, you'll see that it's just one copy of this image, and that's not really going to look like a background Portmore like a tile within the game like these platforms. So in order to make it tile automatically, we can change the draw mode from simple to tiled. Now we need to figure out how far this should be drawn so we can change this size there within the height to something like 30 to 32. And that can get you the result that we were looking for. Now I doubt it's gonna be an issue. But if you're game map is particularly big and you don't want this image to be stretched over some massive area like this, you could simply make sure it stretches toothy camera size and then moves with the camera always being a background but always perfectly size to the camera. But that would be an extra script you need to add, and I don't think it will be necessary for our purposes here. But now we've got a completely different problem, which is that the image here is actually showing in front of the tile map grid. If we go to the game view, we can't see any of the tiles. So to change that, we need to use sorting layers in order to make sure that the sprite render for the background is hiding behind everything else, So it should be the last thing people see if there's no other tiles in front of it. So I've already created this background sorting layer. If you click on add sorting layer, you'll be able to see all of this sorting layers you've created for your game. Generally speaking, I think your background is gonna want to be at the top because it's going to be in the background. Hence, the name persons have already click that button and added that in here, all I need to do at this point is to change the sorting layer to be G now something to point out about sorting layers as well. If you're gonna make a very complicated tile map that say has three or four layers of different styles than these, sorting layers will be very useful for that. To just whatever you want to show in front of other things should be on the lower sorting layer, and that's generally how it goes and order in layer. If you want to order things within a certain layer, then you can change this numeric value as well. To further make sure that everything is in the right positions for your game. So now if we go into the game view, we can see that we have the background here. If we were able to move around a bit off this screen than the camera would move and you would just Seymour copies off this tile, you might need to make it bigger If, um, your map is going to be particularly large. But for most people's purposes were pretty much done here. So I've been Chris. I hope you found this tutorial on adding a to D background in for your game to be helpful, and I was you guys in my future unity content. 19. How to Hide Part of Sprite Animation with Sprite Mask: Hello, everybody closer. And in this video I wanted to show you guys how we can use layer masks in order to hide part of a sprite that maybe an animation using unity. So the basic concept is this. We might have something like a trap, like over here and Mario Brothers, where a giant pillar comes down and strikes the ground. So while it's in its idle state, most of this spike is actually hiding above the ground up here, and then it will come down and hit the ground. So at various points of this animation, parts of the strike are gonna be hidden and parts are not now it might be possible, in many cases, to just hide this bright by having another spread in front of it, such as this background wall that we see up here. But what if you don't have that so you can actually hide sprites inside of unity by using layer masks, which is a built in tool for your game objects. So here I have a pillar trap. But give the very rudimentary art here, and this pillar is going to have two different states, so it's going to have activated state where it comes up here and with theoretically hit or damage a character. And then it has its idle state where it will return to once it's triggered and dropped back down here to the bottom. But then you'll see here I have a layer mask you which will actually hide the east right as it comes down here. So in order to do the animation, we simply adjust the position of this bright, basically moving it up and down. And when it is down, although we don't have anything covering it here like background, it's going to be hidden in the game because we have a layer mask fighting everything below here. So I can show this really quickly by adjusting the position of the pillar. So I'll bring this down, and by dropping it down to zero or around there, we can see that although the straight size is the same, the layer mask is hiding everything that drops below this point mint here. So too sure what this might look like in an animation? I can show you the idol state, so this Idol state is what would be shown until the pillar is triggered So this would be where everything is hiding over here, below the layer mask. And then when you actually have the animation trigger, it will start at that Idol state, and it will play back, going to its highest point and then sink back down east curves air, of course, optional out of the box. That gives you a simple one. So when you have a basic animation here over one second, it looks kind of like that. Okay, so in the actual game object itself, I have pillar trap based. This is where you would want to control the position of the trap. In general, as you can see, although the sprites are split into two different parts this base area right here, everything you see in red. So then on the pillar game object, which is a child of the parent, obviously, in the animation, you can change the position of it however you want, and by splitting your sprite into two, it becomes very easy to manipulate them individually, which can be helpful now to actually add your mask. I have a separate game object also attached to the parent pillar trap base here, and you can see, it's just a basic game object that has a sprite mask attached to it. So for the Sprite, I'm using a simple white square. It's 100 by 100 pixels. And then however much I scale up, this simple sprite to is going to determine the bounds of this layer mask pretty much that's all you really need. I don't think I needed to even change the Alfa cut off point at all. And then once you have your trap animating properly, you can simply attach a box collider for way. You want it to do damage. Use an animator in order to actually move the sprite, and I created a little pillar activation script. So when W. Is pressed, the animation gets triggered so we could play and see how that would look like they're. You may decide that it's not the player who is actually controlling the pillar at all, so I'm going to hit W here, and animation triggers right after that. No, here, the important thing. That is when the pillar is actually down here under the base that it is completely invisible. And to prove that it is there, I will disable the mask temporarily, and you can see how it looks without having the mask there. So if it was like this, that would not be the result we want. And that's why the Damascus is very useful in this case. So I'm going to include a link to this project and the description. You're free to use it. However you wish. I've been Chris. Thanks for watching. And I'll see you guys in my future video content. 20. How to Move Left and Right with Input & Rigidbody 2D Forces: Hello, everybody, Christopher. And in this video, I'm gonna be showing you how to move a character by adding forces to the rigid body off that character. And the reason why we would want a character to have a rigid body with a dynamic mode is so the other objects which may apply forces to that object can work properly. So if we have, like a giant ball coming down the field and it crashes into this character in my apply a force to him and changed the direction in which that characters traveling, that's only possible if we're doing physics through the Richard Body two D or three D. If you have a three D game, so an order for rigid bodies to work, we obviously have to have one attached to the character. So I'm gonna go here and add a rigid body to D, and you'll see it's set to dynamic by default, which is what we want for that kind of physics based play. You notice that has gravity scale out of the box. This means that it will be affected by gravity. If there's no ground underneath the character, he's gonna fall down on the screen, possibly something you want for platform of games, and you can't customize how much gravity there is in the game by going to the preferences of the physics calculations for the game. Let's just take a look that I think it's edit project settings, physics to tea. And then we have ah, yes, gravity. So it has a X direction and a wide direction, and you can see that this is set to be a world physics of next 9.81 You could have gravity to the left, though, if you wanted to. Well, you could have no gravity at all up to you for your game. So now that we have this rigid body to D, we're going to need to reference that in script so that we can add forces to it when keys are pressed. So I'm gonna add component here, and we're going to create a new script. I'm gonna call it player movement for now, keeping it relatively simple. Andi, pointing out This is a script for the player's movement, which probably means in one way or another, it's going to be getting input from the player, whether that's W. A s D on your keyboard or tapping on the screen to move the character. So let's go ahead and add it. This script in visual studio or your editor. Okay, so in this play movement script, the first thing we're gonna need to do is get reference to a rigid body to D. And I guess I just called this place rigid body. There are some default names are rigid body and rigid body to D for basically deprecate ID classes that exist in mono behavior. But because there's air deprecate, it is recommended that you don't reference them. And instead you get the player rigid body by doing something like get component on a rigid body to D. Um, so we could do that in awake, or you can manually assign it in the inspector. But I think in this case will just rabbit and script win. The script awakes, so this is gonna be equal to get component of rigid body to D, and we'll also require the component of typos rigid body to D, so that whenever this script is added to the player, it's going to make sure and add one. If it doesn't exist, a rigid body to D. So right, this should work as long as the rigid body to tea is, in the end attached. Toothy player. So now what we can do is on update. We can check if any of the keys are pressed that irrelevant to the player. And if so, then we can apply some forces to that Richard body. So first off, I'll check if the player rigid body does not equal no, then we'll proceed. And if not, then I want to be logging out some warnings to the council So debug dot lug warning. Rigid body not attached to a player. I guess we could get game object dot thing, But if the vigil body is attached, then we want to check for input. So I could make this a new method called by input. We'll go down here and make that method so public avoid, apply in port, and this method is going to check to see if any player keys are it down and, if so, perform relevant actions. So we're seeing what key settings we have applied to a game. We can go to edit project settings and input, and you'll be able to see the default controls for the game. And this includes stuff or is great joysticks for keyboard controls. And I believe you can set stuff up for, like, external devices as well. If you have, like a game controller. So ideally, we'd like getting the input to not be specific to the controller. But we only care about the value. And then the input manager handles which controller is assigning what value to the import fields over here. So one way we can do that for left, right, up, down movement is to check the access input so we can do get access. So let's get access and the name of the access, I think might be ex I'm not actually 100% sure on that. We'll have Teoh test it a bit. Oh, and actually, this returns a value. So we want to take the float X in port and we'll do that by getting the access value and then we'll get flow. Why? Input and import dot Get access. Okay, so in theory, that should give us a X and white in port. So if X import does not equals zero, then we're gonna want to apply that accent put as a force on the rigid body. So let's get the player rigid Body and AdForce and that force is gonna be a vector to Okay , So in order to apply a force onto the object, we're going to need to create a vector to for that force. And we can do that by creating a new vector to getting an X value and then a y value here. And then finally, we apply that as a force do the rigid body to D. Now, in my mind, I'm thinking it's better probably to do this only once per cycles. So if we have, like a jump going on and X input for moving left and right, we'd probably rather get those values combined them into one vector here and then apply the force once rather than trying Teoh AdForce multiple times and the same script to the same object. So right now we just have the y set to zero. We won't do jumping yet, but with the X input, if the X input is not equal to zero, but with the X input, we can get a X force here, and the X Force is gonna be equal to X and put times move speed, which is a variable will just set up here in a minute and then times, time dot delta time because we only want Teoh. Add a force relevant to the amount of time it's been since the last frame. So if it took one second for frame to occur for some horrible reason, then we want to apply a lot more force, obviously, than if the frame took 1/100 of a second. Since this is applying every frame update Oh, and also now that I think about it because we're dealing with physics here, we should be doing all of this on fixed update, not update so that this will occur a set number of times per frame and have more consistency. Unity does recommend that you do this whenever you're doing physics based calculations. Eso Now we need a variable for move speed and will probably set. This is ah, public variable. So public float move speed when we can default this to one or five or whatever but generally will set this on a character by character basis to determine how fast they should move, and we take this X force. We add that to the factor and then that force gets added here. So we don't need to worry about if this is zero. Because if the X important zero, there's no import, which means off this multiplication is gonna result in several anyway. So basically, if the key is pressed down, then it's gonna move. But if it's not pressed down, then it's not gonna move. Or rather, it's gonna add a force of the object. So the difference is this is more of an acceleration based thing. If the object still has force and play that hasn't been reduced by friction or other objects stopping it like a wall, it'll keep moving. So you can actually in the inspector, um, for the object, you can add stuff like linear track and angular tracked to determine how quickly those forces should fade out. Mostly something you just need to kind of tweak around with here and figure out exactly how you want this character to interact with the world. So one more thing, I'm gonna make this Richard body private because thes script is already grabbing the rigid body. If it's attached anyway, we don't really need tohave the game designer mess around with it. And the editor, we just need to make sure that there is a rigid body attached. Here s so we don't need this to be manually set and we can make that private. So let's go ahead and see if this works settle. So by the looks of it, I have theatrics s name. Wrong. Eso Let's go ahead and take a look at that. So let's see. Input, horizontal, vertical. Okay, said these are the names, actually, horizontal and vertical, though let's go ahead and get that there. And these are names that you can change, by the way. Okay, So I'm pressing left and right here and we can see that it's not moving, or at least it doesn't look like it's moving. So we'll need to debug the script and figure out exactly what's going on there. So I'm gonna add some break points here, attach the debunker to unity, and let's go ahead and figure this out so we can see that it's hitting the brake points on every frame. But it's kind of going to be a pain to debug it like this because this is on update physics calculation. So it's gonna break in here every single time that the game loads. So I'm thinking on easier way to do. This might be to just run some debug logs to the council, and that's depot dot log. Um, if we can get the velocity of the play a rigid body, let's go ahead and do that as well. And for the sake of making it a little bit easier to read. Ah, let's actually label these. Let's see velocity and let's go ahead and save it and hit play one more time. Okay, so we can see that it is getting X force. And why force when we do hit the plus button there? The velocity, however, is remaining zero, and one of the problems with vectors is that you don't really get the floating point value there, and you can see one of the problems with logging a vector to the console is that it does cut off a lot of decimal points, so you can't really tell if this is actually exactly zero or if it is some very small number. So what we can do is instead log the float values so player Rigid body velocity. Thought why? And let's try that one more time. So kind of weird. We can see that it is an infant testament, Lee. Small number. But it's not exactly zero. Let's see if we bumped the movement. Speed up Times 100. Does anything change here? No, it doesn't. And I'm guessing what's happening here is that it's actually stuck on the ground beneath it . So what would happen if we say, uh took this wall ground and moved it down a bit? Okay, so we can take a look at the box colliders that exist over here. Or in this case, um, these colliders air actually a tile map collider. But in any case, it's applying that collider to everything that is on this grid every ill, and we can see that it goes a little bit above the robots feet. But the robot as a bucks collider, which actually goes down below that, so to box colliders air overlapping each other, they're basically stuck on each other. So I'm gonna manipulate this box colliders position a little bit. And actually, um, because currently we're doing a dynamic, rigid body game. It might make more sense to use a capsule collider. Even absolute colliders tend to work better when a character is close to falling off an edge in terms of modern two D game physics. So this may be preferable. So let's go ahead and lower this down and let's check the grid Collider seems OK, We'll give this a shot and see if this works. Okay, so, uh, the robot fell over, So that's something. At least it's not getting stuck in the collider right now. Let's see if I bumped the movement speed up. If it's able to move to the right or not. Okay, doesn't look like it. So one thing we might want here is to add a rotation constraint, not allowing this sprite to fall over on its side due to gravity. So let's freeze the rotation on that character, and I'm also gonna increase the default move speed to 10 so that hopefully if if something is going to happen, but it's a lot more obvious when it does. Okay, so I hit right. I hit left here, and it's still not going. So let's take a look at the collider really quick. Okay? It looks like the collider is above the ground. And you might also want to lower the colliders on the grounder. Change this bright so that that ends up happening are cutting off that little top area, whatever you need to do. Okay. So as it turns out, the only thing that wasn't going quite right now is that the value is so low in the moose beat that the player, um I guess the drag keeps it from moving before it can actually move. So it looks like the current fix was actually to increase the move speed because they natural drag of a dynamic, rigid body object. I was keeping it from moving basically because the drag was greater than the force being added to it. But now that the force the move speed to set 2000 it can move a lot more like what we would expect. And you can see that when I let go of the import button, it's those down on its own, which is pretty cool to that aspect of the physics engine is already included for us. And if I fall off the edge, the gravity goes ahead and takes place so that means, obviously that the character sits on top of colliders like this ground by default. And we don't need divide anything else for that part of the script. So one little detail here, um, having the move speed set to 1000 might be a really big number and kind of displeasing toe Look at. I think usually people like to use numbers that are a lot smaller. So one thing you could do is have a global variable, something like a move speed multiplier. And you can just take whatever move speed you have here and then multiply it by that global modifier before you assign it to the actual character. Well, if you do that, then you need to make sure any time when you actually a sign of force to the rigid body, you need to add in that global multiplier before adding in the final force to make everything consistent. You could do that with a manager class that manages the movement of all characters within your game, kind of up to you on how you want to do that precisely. 21. Limit Run Speed Velocity Cap: So one more thing we might want to adhere. Um, for left, right movement is a max velocity. So let's see here, public flu, max speed iss equal to we could just say 5/2 for right now, we need to tweak the value later on. And so if we add the force and the player rigid body that velocity dot exe is greater than Max run speed. I will change the variable name there. So what we're gonna want down here is some kind of extra function to cap the velocity. But we could actually put that over here because it's not really relevant to the input. It's making sure that the rigid body doesn't move too fast afterwards, so we could call this cap velocity and now will come down here public, avoid cap velocity, and we will do this for both the X and the Y axis. So we're going to be creating a new vector, and this will be so for this function. We're gonna need to get the capped exit velocity and we can set that equal to a math function. So meth. So we consent that two mass top floor, which means takes the takes the lower of the two values. And Woody that on player dot rigid body dot velocity that X and the velocity cap. So, Max, run speed will call that renaming this up here. So, Max, run speed running, of course. Being left and right philosophy. Oh, actually, what we want here is men, I believe, taking the minimum of the two values. So that means if the velocity is above the maximum speed, then it will just return the max run speed. Now, one thing here to know, though, is that if you are running this function, if there's anything that would want to make the character move somehow beyond that Max velocity speed Ah, you somehow have to work with this function because this function is gonna keep trying to cap it. You could have, like, a Boolean value where it's like is capping enabled? Um, actually, we could go ahead and set that here. So why not public Julian cap enabled. And what set that to true. So we could say if cap enabled, then Captain Velocity and we could also be named this something a little bit better. So velocity cap enabled makes it a little bit more sense to me. So now we can take this updated velocity and pass it into the actual rigid body. So layer rigid body dot velocity is gonna be equal to a new Vector three. And that's going to be equal to kept X velocity for right now. I guess we'll set the variables, but they won't mean anything much here yet. So kept why velocity and just refund. We can say cap dizzy velocity, though this is a two game. So that's probably not too relevant and would just set these kept away. Velocity is equal to layer rigid body doctor velocity dot Why and the sea velocity Same for this evil. You play a rigid body that velocity Nazi, and we're just two using these as a placeholder so that if we ever need to set a cap for going up or down speed like fall speed and a cap for Aziz speed for some reason, um, then we can go ahead and ascended in there. Actually, uh, no rigid bodies to d don't even have Z velocity, which makes sense because they're supposed to exist within a two D game world, so we don't need to worry about that. Um okay, so let's see, the philosophy cap is enabled. So it'll Captain Velocity. Let's see if it works here. So I'm gonna hit right here. So it looked like it wasn't going any faster than it should have. But let's make sure by making this very, very slow the max velocity cap. So with cap of 10 we can see it actually does cap very slowly. Oh, but it's only in one direction as well. Um, so that's kind of a problem. We're gonna need Teoh make this an absolute value. So let's actually take meth f dot a bs of both values. Really? We only need it for this value. And then, regardless of what it returns, you were gonna want to multiply it by the sign. So we'll take math f dot sign of player, rigid body. That velocity dot Exe. So the idea here is the initially we just want to compare the the raw value of the velocity against the run speed, and then we take the smaller of one of those two values. But we still want the sign to be relevant because if the characters moving left, we still need to make it negative in the end. So we need to take the sign of the velocity, which is either plus or negative one or zero. I think it could return zero, and it's gonna multiply that over here. So this should work for us. This is a little bit of simple mathematics. Let's go ahead and make sure that that's the case. So pressing right to move it to the right. Okay, and it's those down, thanks to drag, but we can also go to the left. That's good. Now let's make sure that this is working properly by much, playing the speed by 10. Okay, so what it looks like this happening is that the velocity gets applied to the object. It's going faster than it should, because I guess the move speed being added. It's so great that in a single frame it can force it to move faster than they were on the run speed. So we're going to need to work around with that a little bit. But let's increase the max run speed to something ridiculous as well and free Well, we can see that the character just flies off the screen. Okay, So if you want to get around this problem where you increase the move, speed Teoh a ridiculously high number so that it can move faster than the maximum speed within a single frame, Then one way you can actually work around that is to change the force mode when you're adding force to the rigid body so you can do force mode and, uh, impulse, and then that will be limited by this velocity cap, even if that force would make it go so fast that in a single frame it can exceed the max run speed. So let's go ahead and demonstrate that in play mode. So if I increase the mix, the move speed here to 100,000 we can see that despite having an insane force of, like negative 2000 it still kept by the maximum speed. And if I add them X run speed in here, you can see that it's still being limited by that speed. However, we can also see that the forces that need to be added for an impulse based force or a lot lower here you can see that I have set the move speed to 10 and the maximum speed to 10 here as well, and that gives us kind of the movement where it goes left and right, still affected by drag. And it doesn't hit the max velocity immediately. But the numbers need to be way lower than with a four space to force mode, which is the default of force mode to D dot force. Um, but you know, honestly, in most cases, you probably don't need to worry about this because this only happens if you have such a ridiculously high move speed that it would exceed the max run speed because they only need to worry about this if you if you move, speed is so ridiculously high. That and one frame it would exceed the max run speed, so you don't necessarily after way about this so much. It's a first. For now. I'll just leave it on force mode impulse, since it does sort of seem to solve that problem and just for demonstration and just to show off one overload of the function where you actually change the force mode duty 22. Jump Forces and How to Check If Player is Standing on Ground Collider: Okay, so now that moving left invite is generally working, for the most part, let's go ahead and add jumping. So to perform jumping, we're going to need to get the vertical access, which we already did before on DSI. If basically the player is pressing Thea up button or the equivalent on their device, and then depending on if that is pressed up or not, and whether the character is on the ground already or not, we will allow the player to jump. Okay, so let's comment this move left and right. Then we'll have a space over here for jumping. So a couple ways that pop into my head about how we can do jumping one way would be to see if the white velocity is zero. Because if that's the case, then it's probably standing on top of something. But probably a better way would be to see if this an actual collision between this game object and a collectible object, and if it's standing on top of that object. So let's create a method here. If standing on object is true, then we will allow it to jump so we could make this a property. You're just a method. I'll make it a method here so public Boolean is standing on reliable object. I mean, you rename that there. So this is going to need to check the lighters and to check check for colliders. We're going to need to make sure that it has a collider. So I don't necessarily want to force the player toe, have a collider. So I'm not gonna require up here. And the reason for that is that sometimes you might have a character that can pass through walls and therefore doesn't collide with anything. You can, of course, require it if you want, but I will have a variable set for the collider, though. Let's do that here. Lighter or clear Collider. Maybe to be a little more specific. And we will check on awake if there is one. So let's get that collider to D. And so we'll only check to see if it can jump if it as a collider. So if Layer collider exists, then we'll check that collider. So let's see if the collider is colliding. So we can do that with the lighter to D dot overlap collider so we can apply a contact filter there, which is basically filtering out some colliders from other ones that we don't want in the results. So, for instance, if a collider is a trigger collider, a trigger collider isn't meant to actually block game movement. It's only meant to spawn events, so you might want to say filter out colliders that are set as a trigger collider, and it will return a list of results here. So let's create a contact filter to D, and we call this filter to D, which is a new contact filter to D. And I believe this is just a structure so we can into the values in here, such as trigger so used trigger set to feel to contact based on trigger curve, lighter involvement. And I believe you want to set that to false because we don't want it. Teoh Contact. We don't want this to return a list that includes trigger colliders. Um, so let's add that in there as thief filter to T, and we're going to return it into a result survey. So let's create that right here, and we'll pass it in. But we do need to initialize it. So a new collider to D R A. And I suppose for now we can just initialize it with 10 spaces. That should be enough. And so we get the results it feels in here. So now we want to look through those results. So for each a lighter to d the lighter and results we want Teoh check if Director is on top of collider, and if so, then return. Okay, so I suppose what we can do here if it did return that it's overlapping. Um, we could make sure that it's on the same z value because if it's further in the background , like a paper morio type of thing, then it wouldn't be technically on top of it. If that item is way further in the Z background, because in unity everything is still technically three d. So we want to check if the the lighter dot transformed a Z is equal toothy layer collider that transformed dot Z and if so, then we can say that it is colliding and therefore return true. Otherwise, if it gets all the way down here and hasn't returned true yet, then we can return false, not 100%. If this shirt, if this methods full proof or not, but we can try it out for a while. So let's set some description here. Checks if there are any none trigger colliders that are bi lo e player. Okay, so I thought about it for a little while and I don't think that this method is going to work properly. Why would work if you're standing directly on top? But the problem is it would also include overlapping collisions from the laughter right and top. And we don't want those collisions to allow the player to jump. So what we can actually do here is a simple cast where we cast in the negative one, basically the downwards. Why directions So new Vector 20 negative one. And we returned that into the results of it. And we want to use the same contact filter so filter to t and we also want a distance. So this would be the standing contact distance and we could just set that up top to something like 0.1 public float, standing contact distances equal. Choose 0.1 f. And honestly, I don't think this is a value which would really need to be changed. but I guess we're gonna leave it there for right now. So in this different method, it's actually retraining. Enlist Every cast hit two D's, so let's change that here. First, we need to. Instead, she ate the array as a recast hit duty as well. Hey! And the location of the contact filters also changed here. It needs to go before the list of results. Let's see here. And I think the last very bowl still remains that float for distance. Let's double check that. Uh, yeah, that should be correct. So let's change that to recast Hit. I now hit will have a collider so we can do hit dot ca lighter and get the same values there. Okay, so now what this cast is gonna do is it's going a return, a list of colliders that exist below the player at the max standing contact distance of 7.1 . Really, it should be directly on top of it. But for right now, we can let that value be alone. And we also need to check if those colliders have the same Z position to make sure that that object isn't supposed to be in the background in terms of a three D world. I'm not gonna be named this method a little bit, and we're gonna call it is on top of collider, which doesn't necessarily mean that the character should be allowed to jump. So another thing I'm going to check for here if the character is on top of the collider and the player rigid body got velocity of why is equal to zero. So the reason for this is that we want to make sure that the player is not jumping already and that the player is on top of the collider. So I think by combining these two requirements is should give the most consistency. So now let's go ahead and apply a jump force. So the well, we have to set the wife force here. So, wife force and what do you felt that too zero. But if it actually makes it here, then we consent that two white input names Jump speed, IMEs time dot doubt time. And now with this wife force, we can pass that into this factor over here and now we just need a jump speed variable so public float, jump, speed and we just develop that to one here, or we can make them like I don't know. And and 50. I think a character usually jumps a lot faster than it runs for most two D platform of games. And let's see if all that updates in the inspector here. Okay, cool. So we have a new speed and a jump speed. So let's go ahead and hit play and see if a jump button work settle. Do you can see when I hold the W button down that it does actually jump a little bit, but not nearly enough? Uh, we probably need to bump that jump speed up quite a lot, So let's change this to something like 1000. And when it's in the air and too far from this ground, we get an error, which is basically that there is no collider here. So what we actually want is to make sure that hit Doc Collider is actually set here, though, just to hit dot com lighter. And with that, we should be able Teoh have the character jump. So let's give this a shot here. Pressing W, uh, kinda seems to work, although it doesn't seem particularly consistent. Maybe we need to tame the jump speed down a bunch. Maybe in this case, what we actually want is to remove the time. Not doubt to time. Here is this is supposed to be an instantaneous force. So let's see if that makes it more sense. Oh, it's set the jump power to five cause with removing the time. Not doubt to time assured. Remove a lot of the jump power needed to make it go up. So let's see here. Don't power 500 press up. Okay, So when we tried to jump here, we get a lot of inconsistency and how high he actually jumps. And I think I figured out the reason for this is because the white import isn't always set toe one when we pressed down on a control stick or we press w on our keyboard, but we want to make sure that it will always be set to one. Basically, we can do that by checking if the value is above zero, and if so, then we just set the import value here to a solid one. So let's see here jump power we can set times equal to why import is greater than zero and will return either wonders area. So if why import is greater than zero, this value is one. Otherwise, this is zero. The jump power is cereal. So let's try that. I'm gonna hit, but here. Um Okay, so it seems to be consistent, but I guess we have to use the jump our way up. Still kind of weird. What if we make this really big? Okay. Okay. Um okay, let's work on this code a little bit. Her stuff. We don't want to go through the process of checking all these colliders. And unless there's a white import So if the way import is greater than zero, then we'll just say it's trying to jump. And if it's trying to jump, we don't need to do any of that 10 thing. We could just have this be set to the jump power altogether. So let's give that a shot. A bump, the jump power up here to make sure it can actually jump high enough to be Oh, what happened? Okay, so something crazy happened there. Let's bump that back down. Let's see. Jump Power of five. Okay. Yeah, that's more reasonable, I guess when I said it to 500. It went to the moon quite literally. But now this is working quite nicely because the jump is consistent here. So now it's not being determined by how hard I'm pressing on the up button or the joystick . It's only being determined on whether it that's in a positive direction or not. Now, you could also set it to be something like when spaces pressed. Then add it. That might make a lot more sense, depending on your game. Um, right year there. I think this works pretty well. So let me see one of the right values for a move. Speed. Let's try 50. Let's start to slow. 500. Okay, it's being capped by the maximum speed. Right? Um, 10 is clearly way too fast there. Let's see. Five. They're a bit fast. A sedative. Three. Let's see. Maybe we want him to have a little bit more jump power. And the nice thing about putting this on the inspector while where you have the plate bottom running is we can play around with values that won't be permanent, and then we can figure out what values we want and copy those over into the actual project . When we start getting play, I think this is actually not too bad here. Maybe I bumped the jump speed up a little bit more. There is now a jump speed of four, and that seems like a decent duty platformer controller being stopped by the physics on the ground jumps up the right time. Yeah, this is all pretty cool. Um, so that's go ahead and update those values. I think it was 508 and four. Just a B Cheryl hit play one more time, so let's see. Yep, the jumping, the movement, left and right on can also fall off the cliff in Lose the game. Well, the game doesn't technically get lost here. What's really happening is he's falling for all eternity, never to ever. Well, let's just say that's another kind of health for a guy. And so that, in a nutshell, is how you do basic movement with two D rigid bodies inside of unity. So So I've been Chris. I hope you guys have learned quite a bit about all of this. If you don't like having the physics based movement, you can always change your rigid body to kinetic Kinnah Matic movement. And then that's a little bit different and how you script it. But it's not too bad, but that's gonna be it for this. Part of the two toils on setting up basic two D rigid body dynamic movement inside of Unity type and Chris, thanks for watching and I'll see you guys in my future unity content. 23. Collider.Cast - Checking for Collisions: Hello, everybody. Chris here and in this video, I wanted to talk to you guys about an optimal way of checking for collisions with the default collider components inside of unity. Eso The method we're talking about is collider dot cast. So this could be either done with collider to tease if you're making a two D game or obviously collider, which would be for any three D variant of the colliders, and you just call it the Doc cast method, which takes direction a contact filter. So the filter allows you to take some of the other colliders that it make a light into and to remove the ones you don't like based on things such as a layer mask, a reference to every cast hit. Two d m. A. Which just stores the results of this method into that. And then you can check through all the hits and finally, the distance to check. For now, I believe there are other overrides for this, like not including distance. But this kind of makes the most sense for me because usually if you're gonna check for a collision, you want to check a certain distance. So what's really great about using a collider to D dot move collider or collider dot move collider is that there are different components for the colliders that may exist inside of your game. So obviously you can see here on this player game object. Right now, I have a capsule collider too deep, but they might also be, let's, say, a box collider to T, and you're really not sure which kind of colliding you're gonna be using. So without knowing that you can't exactly determine where the collider should be casting from based on its shape and size. And that's where this method is so great, because it will take any two D or three d collider and it'll determine how it should be cast for you. So you just feed it these parameters, and it will let you know if there's a collision or not to point out. Another reason why this is so much better than, let's say, just doing a simple, very cast in a direction. If you have a collider on your object, let's say you have the center of the object right here, right, and you try to do a very cast out north of there, so that's fine. You can get a general sense of what objects might be in the direction. But let's say that your object is already halfway across to the left like this, where the middle is somewhere around here and you check north because you're moving north on a grid. It's not going to detect these tile map colliders over here because it's casting the vague cast from the center or the top over here. But if you cast as a shape, it's going to basically take the shape, put it in that direction, and if inside of the bounds, it collides with anything like you move this half a unit and it checks al everywhere inside its bounds for that collision, it's gonna let you know that there's this collectible object there, and if you use it properly basically not allowing it to move, it fit the Texas collision, then you'll get the results you're looking for. So to show this an actual gameplay since amusing collider dot cast instead of Rick instead of very cast. If I go over here just a little bit where the center is off balance, it's not gonna let me keep progressing there because If we go back into the scene few weeks , we can see if this collider went a little bit of a step further, it would in fact collide. But a great cast wouldn't detect that a very cast would let us go up north or in the case of this character, down below, it would go let us go south and pass through it, which is not what we want. Um, so yeah, that's why I would just recommend using collider to d dot cast As long as you're not using the E. C. S system, which is currently in preview mode, I hope that they'll have something similar to this when it's done as long as is still working with standard you unity components. Then you can just use collider to D dot cast and basically all of the collisions. They're going to be checked for you because unity has already done the math for you. So really useful. I hope you guys learned a bit with collisions inside of unity to d, and you can easily apply this security as well. Once again, just use collider dot cast instead of collider to d dot cast. But aside from that, I've been Chris. Thanks for watching, and I'll see you guys in my future unity content 24. Fireball Spritesheet Animation Setup: Hello, everybody. Chris here. And in this video, I'm gonna be showing you guys how we can take a sprite, she and create an animated projectile from that spreadsheet. So inside this bright sheep, which you can access inside of your assets folder, um, we're going to need to turn it from Sprite mode, single and to multiple. And the reason for this is that being a she has multiple frames for the animation. So I'm going to change it to multiple here. Um, now, typically, in a to de pixel game, you you're going to have some units standard to go by for all of our assets, especially if you're working on a grid. So that could be something like 32 or 64 pixels. Now, for this particular spreadsheet, which, by the way, I'm grabbing off of open Gaymard dot borg, um slash content slash high dash has stopped fire dash ball. Um, it's actually got 512 pixels with by 197 pixels per frame high. So I think what I'm gonna do is I'm gonna set this to 512 pixels because this is a high rez vector Sprite. Obviously um, all right. Now, once again, if you have just like a normal 32 pixel game, then you probably want that to be 32 pixels or whatever the standard is for UK. Now we go into these bright editor in order to actually cut up this sprite sheets so you can see that there's going to be six frames for this animation here, and we can slice it up by going to the top left hand menu. So where it says, slice, you can do automatic, which I think in this case would work just fine. So you do automatic and you can see that it makes the cuts. But in this case, it actually didn't work properly because you can see the the areas that are separate from the main fireball have actually been turned into separate sprites. So for that reason, you may have to do grid by cell size and step, and you can see by the name of this file that it's 5 12 pixels by 117 197 pixels. So that's what I'm gonna make the grips grid size five trolled by 1 97 Slice it and you see , Now we get six pixel perfect individual frames, so let's go ahead and apply that. Now, if you're working on a Pixar game rather than a vector art game, you're probably gonna also want to change the filter mode from Villa near two point and from compression. Normal quality to none, because when you're dealing with those lower as pixel files, you don't want it. Teoh have any kind of filtering, which is gonna blur out your image. You want it to be pick so perfect you wanted to be sharp. But in this case, this is a high rez vector image, so probably can leave it alone as it is for now. So know what we can do is just take one of thes Sprite images, drag it to the scene, and it will create a new game object that we can say turn into a projectile and animate. So in this case, I'm gonna rename that game object, Fireball for the sake of making it more clear what it is and also drag it into the Assets folder as a prefab. Um, Now I guess in this case, because they already have a pre fabs folders set up. It'll go in prefab since step. So if this is gonna be with the objects you can instant, She ate like enemies of projectiles go so that what we need to do in order to animate this fireball is to actually attach an animator to it. So nobody has a straight render and that can render a frame of a sprite. But there's six frames that it needs to animate between. So I'm going to add a new component, um, animated here and you can see that it takes a runtime animator controller So to create that we can go somewhere inside of our project folder and you right click, create animator controller. So this is basically the is what Animator Comptroller does as it allows the different animations that would be attached to a game object to transition from one to another. Now you can have one animation in this case, but you can also set up events, but you can also set up triggers that will happen, such as when it's not moving. Switched to an idol state inside of the animator controller, and then you go from one animation state to another. But that's a little bit more complicated in this video needs to get into. So I'm just gonna call this fireball a C A c standing for animator controller, and we need to make sure that that is attached in the fireball. So fire ball game object is using Fireball Animator controller. Now we can double click this and we need to add an actual animation And so we can create the animation inside the animator tab. We can create it in the project folder, those So in the same folder, I have the animator controller. I'm also gonna right click, create and do your animation. And I'm just gonna call this fireball loop because it's gonna loop endlessly until it collides with a player or something like that. Um, so we're gonna want to check loop here because the animation can loop over and over again, going frames 1 to 6 and back to one. And now, with the fireball selected in the hierarchy that has the animator attached, we're just gonna want to drag in this animation here. So the entry point is going to be fireball loop, and it has nowhere else to go from there. So basically, that means it's going to start at Fireball Loop and it's gonna keep going until the game object no longer exists that the game is possible. So now, to actually set the animation with the fireball selected as the game object, we hit control six, which will open up the animation window. And you can see that the animations that we've attached to the animator controller going to show up here. So fireball loop. And now all we really need to do is to take these six frames and put them inside of the animation. So I'm just gonna left click on one hold shift left, click at the one at the end to grab six frames are at once, and I'm going to put that in there so you can see that there are now six frames created with that animation. Now, as it stands, 60 samples, I believe, is 60 frames per second. So if I hit play here on the animation window, it goes way too fast. I'm thinking something more like six samples or six frames for second makes infinitely more sense, and we can it play. To test that out actually looks a lot better now, and at this point, I believe we're done. We've set up the animation. We could just go into the game view. Uh, let's disable this canvas and the other stuff here. And we'll also increased the size of that fireball so that it actually shows up better on screen s. I'm increasing the scale here, and I'm gonna hit play. So with play is should actually run through that animation loop endlessly. Eso we now have animated fireable. So in the next video, we're gonna work on making this into an actual projectile which will interact with game objects such as your player, maybe collide to it, explode, do some damage, that sort of things. So I think, Chris, thanks for watching this video and setting up a animated projectile. And I will see you guys in my future video content 25. Moving Fireballs with Collision Detection: Hello, everybody. Chris here and in this video, I'm gonna be showing you how we can take this simple game object with a sprite, render in an animator basically a fireable and turn it into an actual moving projectile that can collide with a player game object. So the first thing we're going to do is add component, and we're gonna create a new script. I'll just call this projectile script, keep it nice and generic for right now, and we will open this up in visual studio for editing. Okay, so, inside of this projectile script, we're going to need to set up a few variables. One is going to be a move speed for the projectile because we want the project out to move , and we want to be able to set how fast it's going to move. So I'm gonna call this public float, move speed, and we could default this to something arbitrary like three f. We're also going to want a public enter, or you could technically make it afloat damage and I'm gonna default that to five points of damage. This means that later on, when an object that can take damage collides with the projectile. That character object is gonna take five points of damage, which might mean health in your game. They usually means that. So now how we move, the projectile is going to depend a little bit on whether or not you have a rigid body to D . Ah, In this case, we're going to keep it simple. And we're just gonna update the transform of the projectiles. Game object. Um, that would be when you don't really need physics to interact in your game. Most really typical Trudy games don't need that. If you do need rigid body because you want physics to interact and to be able to apply forces to game objects and when, like project how bumps into something and actually moves that game object, then you want rigid body and stub. But for simplicity's sake, if you want to update that transform here, we can take the move speed and apply it to the position of the transform. So in the update method, which is called once per frame, what I'm going to do is I'm going to update that transformed position. So because model behaviour has a direct reference, toothy transform weaken just reference that without anything else, they're transformed up position. And I'm going to set this equal to a new vector. Three a factor three just means as x y and see court. And it's so I'm going, Teoh, break that into three parts here. So for transform acts, I want that to be transform dot position dot acts the current position, and then I'm gonna add in the move speed. Um, but we don't know exactly how many frames air running for a second. So how we can work with that is to do times, time dot daughter time. And what doctor time is is the time since the last frame that's usually going to be something like 1/20 of a second represented by afloat. So we take these values and we're gonna add that to the position of X. So what this means is that the project I would always be moving to the right because move speed is positive. I guess if you actually made a move speed negative, it would make it move to the left on. We're just gonna keep it that simple for right here. So everything else there y and z cord and it's there was just going to be left as is. And the reason we need to create a new vector for this is that you can't directly change the X Y Z values, as I recall, so we do need to do this. So Transform X adds the move. Speed Times, Times Dr Time Transformed position wise left alone positions he has left alone. And now, while this game object is active, it's going to start moving to the right, which is great. Um, now we can actually go ahead and test that in unity real quick. So we have the projectile script attached. I'm going to hit, play and see how this works so you can see the projectiles moving to the right. Now it's not facing the right direction, which is an issue, but the important thing for right now is that it's moving in the right direction. So now what we need to do is actually set up collision because it needs to collide with the player object, and it should do that as a trigger. In this case, we don't want it to directly block the player. We want it to collide with the player, delete itself in deal damage to the player. Um, so we can do that with on trigger enter to D. So, in visual studio, just start typing on trigger, and it will be able to find that method for you, which all mono behaviors air able to implement. So this method passes in a collider to D as a parameter, and the collider to d will be the thing that it collides with the thing that this project I was colliding with so we can check to see if that collider is of a certain type, which in this case, we wanted to check a character type that we haven't created yet. So before we start fighting this method, I'm gonna want to create another script. And just to make things a little bit quicker, I'm gonna duplicate this enemy game object, and we're gonna trend that into a players. I'm gonna remove this Sponder script, and I'm gonna add a new character script that we're going to write right now so you can see that the character has a box collider to D and ah, Richard body to deal so you can see that this character has a box collider to D already added to it The rigid body to d. We're going to remove that. We don't need it for right now and I'm gonna rename this game object. Teoh. Let's make it player actually on if we can enable. If we want for the future because we want the fly ball to collide with, I'll move it over to the right, and that should make this viable run into it in the future. Now we need to actually at it this character script. In this character script, I'm going to set a few variables. So how do public, Um, let's go an end health and will default that to 50 points of health and will create a method called take Damage. So worried Take damage is going to take an end of the damage taken, and we're going to update health two B minus equal to that damage. So basically, we subtract the damage from the players. Health. That's a simple is you could get, um, and the reason we need this is through the projectile script when it collides it, it's going to need to make sure that the collider is something that can actually take damage before it runs the collider scripts. Now, you could also make this an interface. And then you could implement this interface in any model behavior class that you wanted to be able to take damage. You can also use this as a base class and then maybe make a parent class like player that extends character, and then it already has this stuff included. But we just keep it really simple for right now. So health and take damage. I think that's all it's gonna need for right now. So now what we can do back on the projectile script for on Trigger Enter to D is we can check if the collider to D contains a character script. Basically, if the game object has a character script attached to it. So I'm gonna call this character character as equal to, uh, collision. Um game object dot Get components that we're checking to see if it has the character script attached to it. And if it finds one, it's going to set that to this character variable. And that will mean that the character variable is not know. So if character is not equal to know, then that character can take damage. I forgot to set it to be a public method. If you want it to be able to be called from other scripts, it should be set to public. So character dot take damage and we're going to set the damage taken equal to the damage that the projectile does up here. And, oh, and the final thing we want to do is actually remove the projectile because it's not ah, every frame thing. It's a collide once and destroy the projectile thing. So let's do destroy game object here. And that's of course, referring to the game object of whatever this script is attached to. So with that, uh, if I'm not wrong, okay, the fireball doesn't need to have a box collider. But if I'm not wrong, that should be out. The scripting we need. Here s so we do, of course, need to add a box collider to D to the fireball. So I'm gonna add a box collider that the glider shape is just to determine where the bounds of where can collide at our and you can only see that. Of course, in the scene editor, it might make more sense to do something like a capsule shape because it is a bit round off dull. But I'm gonna take this collect collider bounds, and I'm gonna make it a little bit more reasonable here, Uh, make it so that only the main parts will actually deal damage and remove the projectile. So let's say that there and it should be, is trigger. And the reason we make it is Trigger Inbox Collider to D is so that it can interact in terms of physics. But something passing through it can trigger the on trigger inter two D method. So basically, it only serves to have something happened when something enters it, which in this case, if it's a character, it's gonna take damage and then destroy the projectile. So let's go ahead and hit, play here and see if it works. Do. And it did not collide for some reason. Let's find out why that IHS okay, Okay, after messing around with it for a little bit, what we needed was a rigid body to D set to Kinnah Matic mode for the player. So to cover rigid bodies really quick, dynamic rigid bodies allow physics to interact with it. You can have things like gravity and objects can push each other. And Kinnah Matic objects have to be moved specifically with the script. So that would be things like doing transformed dot translate on a game object in order to move rather than applying a force to the rigid body to tea. But in any case, a kid, a Matic rigid body see out of rigid body to d, and you make the body type automatic, we'll allow the collision to occur between this game object and the player. So what's it gonna gonna correct the rigid body? It a little bit. One more thing I want to point out. Here is what I was looking through. Some of the documentation transformed out translate is actually a better way. Teoh apply a change in the position of the transform. So rather than creating a new vector with the updated values, you could just change the values by translating or moving it in the directions of X y Z. So in this case, I'm adding in the move speed times, doubt to time on every frame and nothing for why, and nothing for sea. So it does. The exact same thing is this up here, but this is probably a more proper way to do it. So let's go ahead and play this one more time and I'm gonna click on the player if they can , to show that the player does take damage here. So, uh, where's the player script? Okay, Character script. You can see it. The base houses set to 50 but because that projectile was able to interact with it took five damage and the projectile was destroyed. So one more thing I want to show regarding projectiles would be how to add a sound to them . Now, on my gum road, there's a audio script that allows you to create audio sources on demand. But if you want to do it the classic unity way, then you can do so by adding in a audio source component directly onto the projectile. So with this audio source, you're going to wanna play an audio clip. Of course, you can click on this little circle over here to select sound effect from your game assets library. So I'm gonna select this fireball sound effect. You want to turn off, play on, awake off, and we actually want the sound effect to trigger when the fireball collides with the player . So in order to make this sound effect play when they collide, what we can do is add in a reference to the audio source here. So I'm gonna call this out of your source out of your source and we want to get a reference to that on awake. So under your source, Eco's get component audio source. So that should mean that now for this productive scripts, you should have audio source attached to it. Caps matter. Careful there. And now when they collide, we're going to want to take the audio source and we're going to want to play whatever sound clip is inside of it. Now there's gonna be one more issue here, which is that if you destroy the game object immediately, What's going to happen is that three audio source will be destroyed along with it, so you won't hear this out effect. And that's one thing that the gun road out of your script I've been talking about, which I have other tutorials on helps with because when you use that you can target any transform toe, add the audio source on to rather than having the audio source have to be on this game object which is about to be destroyed. So actually, rather than setting the game object inactive because that will stop running the scripts on the game object. Ah, better way we can do it would be to take the collider to d attached to it and the strike render. And now that I think about it a little bit more, rather than setting the game object to false because I think that all stopped the scripts. What we should really have happened is that the render attached to it and the collider attached to it would just make those inactive rather than the entire game object inactive. So what we can do here is do you get component on the sprite render so we can take the sprite render and set the color the outfit to that s o just like the position. We can't set the individual properties of the color individually. So I'm going to do a new color and we'll make it 1111 which is perfect white, but with full Alfa. Oh, wait, We're sorry. We want no Alfa to make it completely invisible. Um, And then we need to get component on the collider to D, and we want to make that inactive, so enabled equals false. This is going to mean that this fight will be invisible and the Game collider can't collide anymore. And then before we do the final destroy on the game object, we can take the audio sources clip length and weight that many seconds. And finally, in order to start triggering the final destruction in the update method, we can say collided equals true. And we'll need to create that Julian up here. So collected Boolean. That should default to false. So this is gonna be set to true after it collides. So if it's if it's collided, Okay, so now what we want to check in Collided is how much duration has occurred with the audio clip being played. So one way we can do that is audio source got time, which is going to give you the playback position. So if that is equal or greater than the clip length, then that's going to mean that it's done. So if audio source that time is greater than or equal to clip length, then we can destroy the game. Object. Okay, so with this implementation, it should, in theory, work and the update method will keep being able to be called until the audio source is finished playing. But I'm going to do one more thing if it hasn't collided yet, I'm going to update the transform. Um, this is just kind of more for good practice, you won't be able to see it, and it won't be to collide with anything, but we really don't need the projectile to keep moving invisibly while it has collided. Um, because we're only keeping it in this scene so that it can play that sound source. Okay, so let's go ahead and test this out in the actual game. Okay? So as you could see, the fireball collided. It turned invisible. It wasn't able to collide anymore. So the players south is still 45 it remained in the scene until the audio clip was done playing, and then it destroyed itself. So that was exactly what we were looking for. Okay, So one more thing I want to change here is that the projectile should be facing to the right because we are applying a movement to the right. So I'm actually gonna flip the acts on this bright render. So it's always facing to the right and we're going Teoh, change the box collider and make this face over here as well. Um, now with this, if we were to say rotated later on, let's say 180 degrees and we were moving in the same direction. It were just moved to the left properly. So really, the only thing that has happened is that the flip act should be checked their for this particular sprite. Just make sure that your spite is moving in the direction that it's actually facing eso. In this case, uh, you can probably just go ahead and hit play. So I'm gonna hit play, we'll test it out, and then we'll kind of duplicate things a bit. Okay, great. So now with this one item, we can duplicate it. Ah, lot. And go ahead and hit. Play one more time. Okay, So that's pretty much all there is to creating a basic project. I own side of unity, so I think for us Thanks for watching. And also you guys in my future video content 26. Projectile Physics - Curved Path and Returning Projectiles: So let's see. Okay, I didn't quite get there. OK? Yeah, You see, way not get back. And on their land. So there. Okay, so the first thing we're going to want to do here to add physics to our game and to allow this object here, the car to be or to be affected by things like gravity or other forces acting upon them is to add a rigid body to d component to our projectile. So in the inspector over here, I'm gonna go ahead and add in a rigid body to D, and it will be set to dynamic mode. Dynamic mode means that regular forces will be act on it. So if we in another script to do something like add force of 1000 to this, it will be able to apply that force and be affected by things like linear drag, angular drag. Ah, and as long as gravity scale, it's not set to zero. Gravity will also still be an impactful force on that object as well. So a dynamic, rigid body makes it pretty easy for our game to get physics that are kind of similar to something like you'd see an angry birds. So it's generally the way to go for a complex studi physics. Now, in order to make this object launch, we're going to need a script to do that. It could either be on the object itself, but generally we would have other objects. Apply the force to the all right. But if you were to think about it logically, usually an inanimate object doesn't make itself move. It's an outside force to ask to act on it. So just to simplify things, we could go over here and create a new empty game object and make sure it's not nested. And we could just go this God powers where anything we want to be able to do seemingly from nowhere as the god of this world. We could do that through this God Power script, though. Let's create that here, and I'm gonna create an ad and let's open it up for editing. Okay, so now that we have this God power script open, we can go ahead and give us a functionality. Um, so what I want this God power script to be able to do is to apply a force to our target, causing it to move. And the target, of course, is going to be this cart projectile. So the first thing we're gonna need to figure out is our target. Now, there would be many ways for selecting a target, but, um, to make this video a little bit simpler, I'm going to actually will make this a rigid body to be. And I'm gonna call this target. So in order for it to be a valid target has captivated body to de because you're applying a force to a dynamic, rigid body and then we need a function at a function to actually applying force. So, uh, let's see here, public Boyd, apply force, and we don't necessarily need to pass a parameter of a target because we already have that set in the script. So we can just reference the variable set up here. But what we might want is a float value of the force. So how much force do we want to apply to the target? And we might also want a vector two of direction, so we'll have a force and a direction to apply that. And now all we need to do is add the force toothy target. So let's see here, Um, it needs to be affected. Two of a force. So that will be the direction times the force. So all we really need here is direction Times Force here, which returns in new Vector two D at the correct values. And that's actually it. I think that that's really, really simple there, but we actually need a triggering event for the supply force method to be caught. So one easy way to do that on the update method would be to check if the input key is being held down. So if import dot get key down, So if this keys down, I want to start getting ready to apply force. But I don't want to apply it yet and said I'd rather charge up the force for set amount of time basically until the input key is released. And then once the key is released, it's going to actually fire Jack Tile or apply the force to the projectile and will make this a private Boolean and charging, which he faults to false up here. And so if charging it was true, then we want to get the time charged. It's going to be plus equals. I am got down to time. So basically the time since the last frame. And this needs to equal signs because it's checking to see if true, not assigning it and also the time charged your default to severe every time it started starting. Let's see here another private float, time charged. And another thing we can check for here. If the input key is not down, it might be up so we can check if the key was released, that key up Geico dot space And uh, let's see here. So if the KIIS up, then we want Teoh released the charging and we also want to apply force. So let's see here. That's going to be I'm charged Times force multiplier which we haven't created yet And then the direction will figure that out in a minute here. But I guess we'll just make that another public variable direction for now. And then after we apply the force, we want Teoh make time charged, and then, after we by the forest, we could make time charged equal to zero. Probably redundant. I think we only need to apply either here or here, but it doesn't really hurt anything. I guess I only have it there once, since it's unnecessary. Let's see if bridging is true. Time charged. Okay, so now we just need these variables up here. So let's see a force multiplier. That's something we can allow the designer to set in the Inspector. So let's create. Actually, we can make it a float, so force multiplier and public vector to direction. So we'll need to set those values and the Inspector. But aside from that, as long as we set these three values, whenever we have this God power script created an hour scene, uh should probably work. Let's go back to the inspector and see what happens here. Though we need to set a target so we can select that for the card, since as a rigid body, uh, also be naming the car, it would probably be a good idea. Let's go it right projectile. Let's go back to guard powers, the force multiplier. I honestly don't know how much force we need to apply to that car to make it move in a reasonable fashion. So I'll just try that at 100 and, ah, for the direction. Let's start off by having it be want one in the X, which means it's going to be going over this direction and let's go ahead and hit play and see if this works at all. Okay, so first off the cart fell through the floor because I have no, actually added in the title map collider here to this ground. Let's fix that real quick, though. On the grid I Oh, man, we just want a tile map collider to D, which will stop objects like the cart from falling through. But that will only happen if there's actually a collider on this card as well. So on the card, I'm going to add in, Let's say, a circle collider and let's resize it a little bit so that shape seems more reasonable. And now let's go ahead and get back to our scene. Okay, I'm gonna hold down space and let go. You can see it rolls along the surface there. Not too bad, not exactly what we're looking for having a curve projectile, but it definitely is moving. Um, also, it might be cool to have a little text indicator here about how long it's been held down, so I think. What? Actually, add in a text you I component, Um, so let's add this year and will add it to the top left of the envious inch, the color to white and will make the front any bolt, which is a free thought. You can get on mine and I'm Howard down are charging time and that will, of course, be defrocked in several. But really, what we're going to need to do is control that with our God power script. So here I'll add in a X component, bridging text and using unity. I using a unity engine dot you I if this is set than on update. We want to set the text, though. So if charging text is actually set, then charging text dot text is going to be to basically this value plus the time charged. But we might want Teoh allow someone in the inspector that change this value. So I'm actually going to replace that with a public variable So we'll do a string and we'll call, uh, charging next and true, I guess, and we'll set that default value to that charging time hero. Also, we should remove those extra characters so actual value here is going to be urging text intro, plus time charged. And I think with this text we can go ahead and anchor in the top right hand corner and push it away from the side a few pixels. So I'm gonna offset it 10 pixels away from the top left corner and on the God power script , you can reference that text. Now, we might want a better way of doing this. Obviously, if we're manually referencing every object on our screen if we remove those objects than we've run into problems. But the key things really, really simple here for testing purposes, this is OK for now, Um, something gonna also be named this text charging text to make it more clear what it actually does. And let's hit play and let's hold down. Okay, so we can see that the text is changing, but, um, it doesn't actually update there. And the reason for that is our text. It's simply too small, though, but stretch it out a bit more. You know, we just want to put this car at an elevated space and add an extra brick underneath here so that when we apply, the force will actually be able to see a little bit of occur because gravity will be applying on this while the forward forces also applying on that. And that's where dynamic, rigid bodies. I'm good. Ah, and then we'll actually make it so that when we apply a force here, we'll get an actual curve. Uh, something like this that will hopefully reach this caveman guy over here and then later will be ableto have him bounce it back to the starting place. So let's go ahead and add in a couple extra tiles here. Not gonna worry too much about the article. Yeah, at the moment. And then let's get the cart. Some were on top of there and we'll hit, play and test one more time. So the charging is time. Still not really updating that well, but you can see how when we fling that car off the cliff. Um, there was a bit of a curve there, and that's all due to the gravity. So the problem here with the text is that the flow is trying to show every decimal point which is going way too far for the space we have in the campus text. So what we can do here is actually cut off some of the decimal points. So how we can solve this problem of the flow having too many decimal points is to do a two string method. And then we pass in a string of basically how maney decimal points we wanted to have. We could do 0.0 and that's gonna be afloat with two decimal points. So let's see if that's still working over here and they mode. Okay, so we hold down the and has two decimal points, so that's pretty much exactly what we're looking for. So now we want to actually have this card lunch in a arc so that it will kind of land over here on the cake. Man, we wanted to go up and then come down, and obviously the easiest way we can force it to come down is to have gravity in our world . Um, so I'm going to change the direction to one and one, so this means it's gonna be going in this direction initially, we can actually make it a little bit more high than it will be far. By reducing the X. Now this instead of 11 it's something more like 0.81 and if we had 01 it would be straight up. So let's go ahead and try this out, so I'm gonna charge it up a bit. And let's release at four seconds, Okay, Pretty close. I think we need about 3.5 seconds in order to hit that player object over there, but in order for it to hit that rigid, but in order for it actually contact with this character over here, the characters also going to need its own rigid body to de um, we will leave it as dynamic over there. And let's create a It's a capsule collider that usually works pretty well for characters that are taller than they are wide. So let's adjust that a bit and let's see if we can make that hit this character over. So 3.5 seconds, and what I expect to happen is that they'll apply force to each other. So this guy got knocked off the cliff very much angry birds style and and the cart bounced backwards, which is pretty cool, eh? So you can see how complex physics interactions are made really simple, with unities, rigid bodies. But now the final thing we want to be able to do is to have this character and knock back the car to its original starting place. And we might also not want this character to move so much. There's a few ways we could do that. We could have this rigid body actually be akin a Matic Richard body where it would not be affected by forces and then in script. We would have it apply a force back over here. We could leave it as dynamic, and we couldn't massively increased the mass so that it will become a character where basically, it is very hard to move because it would need a large amount of force to move that mass. We could also increase the linear drag so that if there's any force applied to it, it fades out very, very quickly. Um, so there's very few options there, maybe. Oh, increase the mass by 10 and linear drag by 0.1. I mean, it is on a surface here, So there would, I guess, be some drag or attention due to that. But Now we're gonna want kind of a reflection script. Teoh, knock this projectile back over towards the starting point. So let's great a script and I'm gonna call it Knocked back. They'll create an ad and let's edit it. So the moment where it is in contact with the other object is going to be a on collider. Enter UN collider, enter to D. And when that happens, we're gonna want to get the rigid body to D of the collision target, though rigid collider the lighters. Rigid body. Yes, Uh, probably can't get a better name for that if you want. And that's do collision dot of the rigid body. Okay, I guess it already had a property for picking that up, so that's pretty easy, actually. If that's the case, then we don't even need to get it, because it's nobody got with this this property over here. But we need Teoh. Pass that into a function. So we're going to call this function knocked back and let's pass in the collision. Other rigid body here and now we create that function. Oh, well, the funk that this has the same name as the script, so but we're trying to give it the same name as the class. So that is going to cause us some issues there. So we could either change the class name or we can change this method we're trying to create. I guess you could call it commit knocked back or something, and let's create that function. So it's going to take this other rigid body and we want it to add a force to it. So the force is gonna be a variable we have to set. So let's make it a little bit simple and this one, and it would just make it a well, let's actually make it consistent with the other one. Let's make it a direction and then a float force multiplier. We can make it a little bit more specific. Knocked back direction and force multiplier. That's specific enough, I guess. So. We want knock back direction times thief, force multiplier, And that is going to be set in the Inspector though the knock back direction Ah, in this case is going to be something like a negative one and then negative 0.5 and the force multiplier. Let's just try it at Oh, I don't know 1000. One other thing I want to add here for fun is going to be that when it does do that knock back, it changes color for a second. So it's like this guy's getting mad and he's knocking back the carts to where it came from , So I want him to turn Brad eso How we could do that is on awake, we get access to the sprite, render no bright renderers equal right, render it equals Get component, stretch, render And let's create a private variable for that. Those right bender And we could even make a color for it to change too. And we call this the enrage color and we could say engage duration as well. What do you felt that to you? 0.1 f, which is gonna be 0.1 seconds. But we also have to see how long has it been paged? Um Oh, float. I'm enraged. Zero and I will have a public void in rage method Ah which would change the color. This enraged method will take the sprite render if it exists and the color will be set to the enrage color. But we're also going to want to keep track of what? The original color waas. So let's do that here. So original color is Sprite. Render Dr Color and let's set a variable. Enraging is equal to true, though the Boolean enraging bulls false and then try that color original color. Well, we don't set that yet. We set that here. Okay, so that'll start engaging. And then we just need a function to stop the enrage, though. Stop and each Or actually I have an even cooler idea for you guys here. So let's do this with a co routine So occur routine is basically when some code runs a synchronously on a separate thread and when it reaches a certain point in the code, it will have, ah, statement that will look like yield return, which means until this requirement has been met, go do everything else inside of the unity engine, everything that's happening inside of the game and then cycle through everything and come back to this script and see if the condition has been met. I think unity actually doesn't really have true multi threading. It's more like you just delay the rest of this script from running and Then you go do everything else and you come back to it rather than it truly running on a separate thread. But I'm not 100% on that. But anyway, a country, our it works at a base level. So we need to make this function and I in numerator because it's going to be running a covert gene and we won't need this. Boolean for enraging equals balls. And we won't need this one for time engaged as well. So it does save us having some extra variables there. So how we trigger this method is that when the knock back happens, we want to start a co routine, and this is going to be the in rage method we call it just like that. So called routine with the method we want to run inside of that cove routine. Um, now, this isn't a true cove 18 yet, because there is no returning of about. You asked either return nor return or yield return when we want it to pause and do other stuff. And where we want that to happen is going to be right here. So I'm going to do a yield return new weight four seconds. And this is where we're going to take that invades duration the enraged duration, which in this case is 0.1 seconds up here by default. So it's gonna essentially wait for 0.1 seconds, and then it's gonna come back and to this script, and it's going to do something which is going to be to return the original color. So Sprite renderers dark color is going to be for every color, and that's it. So this whole curl routine is gonna be if this is bright routine A Sorry, a sprite render. It gets the original color, it assigns the new color, and then it waits for a specific amount of seconds, 0.1 seconds in this case. And it returns the original color to that sprite vendor. So really simple, but a cool way that we only need one method here. We don't need to create a start and stop. We can just have it. I'll be inside of one method here, Um, so, yeah, these could be really useful for a lot of things when you get the hang of them. So let's see here. I think we just need to test it and see what happens when it bounces in there. So we do need to set under enrage color. So I made that publicly accessible. So our inspector guy can go ahead and choose this in page color for the red. Uh, let's just make it a really deep red over here. Don't know exactly how that will look, but but it should be OK. And of course, the Alfa. We want that set 2 to 55 so that it will actually still be a visible character. So let's try to make this new. What happened there? Okay, I'm not certain, but I think that might have been due to the capsule collider shape there. Um, I'm gonna try freezing the rotation here so the character can only move left and right. It can't actually gulf rolling around like that. That doesn't make much sense. Maybe it was the angular track and not 100% sure. Let's just play around with it a little bit and figure it out. Um, okay, so it looks like there's a force being applied to it. It's actually take out the freezer Tae shin, And just that this character fall down and then see what happens. Maybe it was because it was stuck. Okay, you know what? It's the knock back script itself. So the commit knocked back. Um, so in the knock back script, I think other rigid body is actually referring to this rigid body and not the one it's in contact with. And secondly, we don't want it to apply to Ground Collider. So I guess we'll need to filter out a little bit. No. First off, let's do the collider dot rigid body. So let's get the collision collider attached rigid body and see what happens here. So right now, I believe this would be applying the force to the ground. But the ground obviously can't move because it's a tile. Um, object, for instance, that too. Yeah, OK, that makes sense. Um, so let's check if there's even a rigid body on the collision collider. So rigid body to D collider body is equal to collision. That collider dot attached body, though if a lighter body and we will commit the knock back. Otherwise we just kind of ignore it. Let's get that rigid body to d class. There s no we're basically just filtering out that this knock back will only happen on anything that has a rigid body to G, and I guess that's fine. You could go another step and make it so that, like you only, um, allow commit knocked back to occur. If they have, like a specific tag, like if they attacked with projectile or if they have a specific script on them. Basically, however, you want to filter it out, you could do that here, Um, but let's see if this is good enough for our purposes here. So I'm gonna say that script again and we'll go ahead and hit play. Okay, so nothing to weird's happening. Let's try getting the court to actually hit that player, though. It's 3.3 who That was a nice knock back, but not quite in the direction we wanted. And he still went flying off the cliff. So maybe this guy needs a little more mass and linear drag, and let's also change that direction. Let's make it a negative one, and then negatives is 0.5. So let's charge up here and he hits it. Okay, so this knock back direction, that's actually negative. Why? So that's right he's punching it down to the ground. We want it to be up and to the left. So right now it's something like this, which is kind of what we're looking for. Let's try this one more time, Okay? So not bad. Kind of close to what we were looking for. Maybe a little bit too much. Why? And a little bit Too much force. I will try it again here. And Yeah, that's pretty close to what we were looking for. Now, if you don't want this guy to move at all, you could just freeze off the constraints. Now, if you don't want this guy to move at all, you could just change the body type to a static, rigid body which was still be able to interact with this car over here. But this itself will not move, though. Let's try demonstrating that that this time, when we charge up and land on him, it should only move the cart so you can see the rage happens. But this does not move at all. So kind of up to you on how you like it. I'll even eyes dynamic, cause I think that looks a little more funny. Okay, now, one more thing. Let's say that with these forces, you wanted to make sure that this car will go back in the exact direction it came from. And you want to completely discount the forces that are acting on this cart when it gets here. So basically, you want to control exactly what force is going to be coming over here to this location. Well, we could do that pretty easily here, So I'm gonna add in an optional piece of code, you can run here, which is going to be too eliminate force. We're going to do that on the 30 collider body. And actually, let's make that a public variable eliminate starting force, and that'll be a Boolean was set to true. So if we have that set, then we will actually run this method otherwise will discount it so you can choose whether or not you want that to be there. And let's make this function here. So eliminate force that takes a a rigid body to D. Actually, you know it making an entirely separate function for this is probably overkill. We could just go on the collider body to D here and I think on this collide this collider body. What we want to do is set the velocity to, uh, well, basically vector to 0.0. Do we want to take all of the force and eliminated before we actually add in this Knock back four. So that guarantees that the force acting on the object after this will be exactly whatever the knock back forces and that there'll be no other outside forces. Now, of course, gravity will continue to affect it after it exits dysfunction in a couple frames passed by . But at this point, we will know what to expect, I believe. Anyway, let's see if that actually works. So I'm going to launch it at this guy here and let's see if Okay, so that was one version. Okay, so we just have to test this a few times and see if at all times the exact force was back consistently and so far it seems to be doing its job pretty well. And then we just going to need to find tweak the numbers. So let's see, Lips didn't quite get there. Okay, but yeah, you see, it kind of goes back in the same path because as the same force applied to it Now what we could do you hear is just lowered the force down a bit like to 400 or something, and we knock it back and lands over there. So as far as using dynamic rigid bodies and applying force is go. That's how you can lunch a projectile towards an area and then have something. Knock it back. Now, you might say, Make this guy into a baseball player, have him swing a baseball bat with an animation, and then only if that baseball bat is actually swinging will allow the knock back function to occur. But this should give you a really good idea of how you can get these kind of interactions going now if you do need, ah, your projectiles to follow an exact path than what I would recommend for you is to. Instead of using dynamic, rigid bodies, you use Kenna Matic rigid bodies, and then you could define paths or target positions for an object to move to over time. But so Kinnah Matic rigid bodies don't use forces, but you would instead modify the position of the object directly, and you would do it on the rigid body like Richard Body position set it to a new position 27. How to Move a Kinematic Body with an Animation Curve: Hello, everybody. Chris here and in this video, I want to show you guys how we can make a Kinnah Matic rigid body follow a curve or a precise path between one point and another point so we can have easing for this curve. We can make it wobble if we want, basically whatever kind of path we want our object to follow. We can do that through scripts, so this isn't strictly an animation. But if we take a look at the code that I wanna had and wrote, we can see that it uses thes properties called animation curves. The animation curves allow us to set values against time, so basically or any time during the course of the script, it's going to have a certain value. So this curve is for the X value, and you can see it's got some curves. Here you can set default curves by changing this kind of thing around that control seat. You do that, um, and you could also add in extra key frame points. So if you wanted to have a more complicated animation, just double click on the curse somewhere and add in your extra key frame and then for the white curve. We have this where as it occurs between zero seconds and two seconds, it's going to go up and then it's gonna come down. So this allows us to precisely control something like a jump where it goes up and comes down. Ah, for one of those values, you could, of course, that in a z curve if you wanted to make this three d as well. And we take these values at the given times and we apply that to the starting position of the object here. So basically, whatever the starting position is, we add the value that is at whatever time, 0.1 seconds, 0.5 seconds stone and so forth. And we add that to the position you get a new position creating the curve that looks something like this. But you can, of course, expand out the values. If you want it to be a longer, uh, effect, then you just move it over here. If you want it to be more dramatic and powerful than you, increase the X or Y values, though, to play it one more time before we delve into the code a little bit here. You can see the path that's following it moves over on the X, but with the why it goes up and then it comes down exactly following our curves over there . So if we take a look at our script here, we, of course, have those animation curves. You need one for each value because it's a value against time graph. So one graph per X y court in it, Um, and we're applying those values to the rigid body. If you're using kinetic, rigid bodies, it's recommended that you change the position on the rigid body rather than the transform itself. That will help you a lot. When it comes time for things like your lighting with other objects, you'll get none of that unwanted, choppy effect and things like Pixar games, where when one object tries to move into another, that kind of kicks it back out as it bumps into the wall. The rigid body to D will prevent all that, and then we have a curve position here, which I think is actually unneeded. That might have been something I had in the original script but didn't actually need in the end time elapsed here, obviously, for determining what point in the curves it is currently whether it started or not. And then we, of course, need to get reference to that rigid body. So on awake we get the component rigid body, so it should be attached there. And we could even add up here a attributes required component, type of rigid body to D. That would be good idea because the script does in fact require that eso then the work actually comes down here in fixed update. We have this starting function, so basically, if it's not started yet restored it, which sets the time elapsed to zero, and we get our starting position on every other frame. What we do here is we add the time duck down to time that time since the last frame, and we set the time elapsed to the positions and the curve. So we get the value from the curve, we evaluate it based on the time that has elapsed. So if 0.5 seconds has elapsed, we get the X value in the white value uh, at 0.5 seconds, so that will give us basically how much value the starting position should have changed over time. So our new value becomes the starting position loss. Whatever the value is at the evaluated time for both the X and Y positions. Now you can get a lot more complicated in terms of curves looking at the key frames. But this is definitely the easiest way to get the value out. So I recommend you use the animation curved without the wait method, and it's really, really simple here. So we said that as a new vector to for the new position that our rigid body has so bodied up move position to this new position and then that's it. So our new position is going to be completely controlled based on this follow curve. Now, obviously, I'm having this occur on the object. As soon as the game loads, you could have this be something of an event where has to come into contact with something like on trigger. Enter two D. Then you start this method and run it on the object. I so that would be a decent place to look at after this. But this is the result you get with what we have so far, so really easily being up to create Irv based movement on an object that is a cinematic rigid body inside the unity. So hopefully this helps you guys out quite a bit if you're trying to make curved movement without relying on a dynamic, rigid body without using the unity physics inside of your game but rather using automatic movement. Uh, so I think Chris, thanks for watching, and I will see you guys in my future unity content. 28. Making a Main Menu - Setup: Hello, everybody. Chris here. And in this video, I'm gonna be showing you guys how to create a start menu from scratch. So let's just go ahead and get into it. Um, inside of your scene, if you don't already have a canvas, you I element you're going to need one, and it should be enabled while you work on it. So if you don't already know the canvases for displaying graphical user interface items basically anything that doesn't interact directly with the game but is rather more of a display showing text on screen images on screen, uh, laying out anything to the user like an options menu that almost always goes on the canvas . And then game objects would exist outside of the canvas, and you can see that they work. You can see that they work on different scales because if we look at the canvas in all items under it, I don't have a wrecked transform instead of a regular transform, and this is measured in pixel, so you can see this is set to 6 40 pixels by 36 60 pixels, which is the size that the game is operating at right now. 6 40 by 3 60 Now, yours might be way higher than that because you're not making a pixel game. But just know whenever you're talking about the wreck transform, you're talking about pixels and then everything else and you're seeing like character is just gonna have a regular transform, which is dealing with unity units, which is measured more on this grid you see in the background one square being one unit. So because we're trying to build a menu, we're going to be building under the canvas element. So what we can do is right. Click on that, go down to You. I, which is going to contain everything that can be attached to a canvas out of the box, and we can start by adding a panel element to the canvas. So a panel services both the container for child game objects. So if you wanted to add something to the panel, you would right click on the panel and add it there like text or image. But you can also see it has an image script attached to it, and by default it stretches the entire canvas, so it's basically a background image off a color so If you ever want to change this to arm or custom image something that, actually, as are on it, you can click on that little icon there to select an image from your project, and you could do something like change it to a fireball with basically transparent areas. Now that's probably not what you want for the background of a panel, but just know that you can do that. They're probably a little more relevant for prototyping. As you can click on the color selector here and just change the background color to whatever you want. You can also increase the Alfa. You'll notice that the panels are set with the default Alfa of 100 which is about 40% of Pass it E, which means that it's 60% see through. And you if there were things behind it, let's say parent game objects. You would be able to see those so to kind of demonstrate how that works. I'll just add a secondary panel here, and you can make the panels, by the way, not be a fully stretched directed transform, but something more like a custom shape size. So if I change it to just center, but with specific sizes here, I could do something like 201 100. And now we have a panel with a specific set size here. And you can see that because this panel has a default capacity of about 40% we can see some of the color of the one behind it coming through. And that would be especially evident if we increase the Alfa on the parent panel. So one thing we could use a secondary panel for would be something like a header bar. So if I click on the anchor presets icon over here and we change it to be top center, it'll bake a little bit more sense if we want to make this a top bar, and we can also click on stretch horizontally over here on the right. And if we hold down all to set position and click on this stretch icon over here, we can stretch the horizontal dimensions to the size of its parents. So if we were to resize the parent panel now like, let's just say, let's say we stretch this end, you can see that the child panel is now going to reflect whatever its parent sizes. So setting certain elements to stretch an anchor presets will be helpful When you're trying to resize your you I where you game in u two different sizes. Um, now, in terms of high, If we wanted that to be a set size weaken, decrease that size to something like 50 Of course, we're still talking about pixels here, maybe 75. And now we can have This is one game object to add Children to. And this is another game object. We can obviously add more Children to, um so a lot of game many is obviously gonna have a close button. So let's right click on the parent because this orange is pretty ugly. I'm gonna change it to something a little bit more eye pleasing right now. We're actually just leave it kind of a gray, I guess for now and for the top bar will want to add something like a title for our game. So we can right click on the top bar, go down to you I and text and we can give it a game title. So I'll just go this tutorial game and be very unoriginal there. Uh, you can also align the text with these alignment tools Years I'm going to align it both horizontally and vertically in the center, and I'm going to actually stretch this element to the bounds of its parent. So that's going to mean that the space of the top bar is also the space of the text for now . So one option for controlling the text size here is to hit best fit, which will try to adjust the text size automatically. Depending on this display resolution of your game, which obviously can change, you might. Your player might have it set at 1920 by 1080 pixels. Or they might be on the order computer, and they're running it at like 12 80 base 7 20 pixels. So best fit is one tool you can use for that to have it automatically resize as an alternative, you can just hard code font size rather than having it be within a range up to you what you want there. And you can also increase the max size and the men size on that best fit. So since we're talking about a main menu here, we're probably gonna want a bunch of buttons like one for starting a new game, one for saving and one for exiting the game. So let's go ahead and create those here. But when I think of a menu, I also think of layout, which could be either a grid layout or vertical layout so vertical would be top to bottom. A list of buttons that will be displayed at even intervals and Gridley out would allow you to have multiple columns so it could be like First Britain Second Montaigne, third button, fourth button up to you. What you want to do with that exactly. But we can create that, but going Teoh. But if you want to create a layout toe, organize your buttons. You can right click on your panel, and you can do create new empty and then in the inspector for that game. Object. We're just going to add a component, and you can type in layout and see what's available to you. So there's Gridley out horizontally out and physical layout. I didn't mention horizontal layout. That's the same is vertical Leo, except it's going left to right rather than top to bottom, and grid allows you to have basically little grid squares. So let's do vertical layout Group for now, and we'll leave the We'll probably come back into thes properties a little later, but we'll leave it there for now so we can see how it looks without changing anything. I'm just gonna call this Menu Buttons group, and that's all we need to do for that game Object. But we'll need to add some buttons below for the actual game functionality. So I'm gonna right click at a button right click, add a button and right click at a button. Oh, and for the Menu Buttons group, we're also gonna want to change its size, so it has more space to actually draw these buttons on. So what I'm gonna do is I'm gonna drag these corners to line up with the panel above it and drag it to the bottom of the pan. The main panel as well. Eso Now we can see that these buttons are being spaced out evenly with the space that's available to them. But they're all also hovering on the left and starting from the top with no padding. So that looks pretty terrible. So I'm gonna start by changing the child alignment in the menu buttons group and will make it, Let's say, middle center Now, if you don't like this automatic spacing, you can also change the child force, expand to remove that height component, and now it'll put them close together. So if you still want some space between these elements, you just change the spacing at a bit of that, so you could make it 10. And if you would rather these buttons be at the top of your menu buttons group, then you contingent from middle center toe upper center. And if you don't like, how it's basically right aligned with the top, you can also add in some padding here, and you could add it to all the sites just to make sure that no matter what the buttons, they're never going to get too close to the edge, which would look pretty bad. But now we have three buttons that we can use for things like starting a new game, loading a game or exiting the game. So let's do those buttons individually. So I'm gonna call this start new game load new game, and you can also give some kind of indication that it's a button so you could say, like, be start new game or buttons start new game, whatever makes the most sense to you. So this is a button exit game. We also want to change the text of these buttons so that it actually makes sense. So it's called this a new game, and then this would be load game and this will be exit game. Okay, so now we're going to want these buttons, actually have some functionality, and in order for that to happen, going to need to script it somehow. 29. Coding Main Menu Buttons: So in order to add functionality to these three buttons, we're going to need to create a script in one way or another. Now we can condense this into your single script, which I think makes sense. Ah, it could be a global manager that these buttons reference as long as you add the function to these on click events in one way or another. Now, if you've never added functions to these on click events, you can do it in the editor, and you can also do it in code. So if you have a object that has a script attached to it, like, let's say this button itself, you can reference any of the scripts attached to it and then car method on it so you could call the bottom dot select method, which is going to happen whenever on Click happens. So by doing that, you can have it be something like New game starts, script function, and then you choose the new game function so that when this button is clicked, that function is going to run. Alternatively, you can just have these delegate methods be set in code as well. So it's up to you how you want to do that. But either way going to do it, you have to create the new game load game and accept game functions. So to keep things relatively simple and straightforward, I'm going to create a script and attach it to the parent panel, which I'm gonna be name main menu here, and we'll add a new script baiting ad component. And I want to type in script for a new C sharp script, and we're gonna be calling the script Main Menu. And now we want to open the script up for editing. I personally use visual studio code default and unity, I believe, is either mono develop or visual studio, the full fledged version. So in this main menu script, we either need to get reference to the buttons so we can set the on click event. Or we're going to need to in the inspector reference, the main menu script in each of those buttons to call the main menu functions So you can do that whichever way you want, so you can either do public button, new game button, public button, load button, public button exit game, and then we'll be able to let's say change the on click event and here or when we fall, leave it in the script and the functions which should be avoid functions. They don't have a return type so that we can use them here. We just referenced them down there. So in order to use thes butting classes, we need to be using Unity and Jen, you I And now we're going to create these three functions. So first the public avoid new game takes new parameters public. Avoid load game next door. Have public avoid open load game menu on. The reason we're doing that is that generally if you're gonna load a game, you're gonna have a bunch of different say files. So you would need a separate panel window that you main menu opens up in order to pick which game your game is trying to load, and then finally would do public void exit game. So new game and exit game can be done pretty easily at a very, very basic level. We can reference the scene manager which we get from unity engine dot seeing management and we can load scene which ever seen is gonna be the 1st 1 into your game, and you would just load that with the default values for that saying so later on. If you have, let's say, a database of all the game objects that should load in that scene when it first starts. You can load that at this time. But for now we're just trying to put some really basic functionality into that because serialization and basically game defaults or what objects should pop up in this scene is, ah, whole another story. So in order to get the name of the scene from whoever is designing the game and the inspector, we're going to set a public string new game seen name here. So wherever the script is attached, they'll be able to set the name of the scene, and then we'll pass that into the new game. So basically, whatever the new game seen name is set for it, that's gonna be the first scene that this function actually load. So it'll just load straight into that scene, and then after that, you can do things like load up the default values for that sing. So the exit game function is also going to be very, very easy. We call application dot quit, and that's pretty much it for that. Um, no. Now you should know that this function will only actually work. If you are working in a compiled version of the game, Not in your editor. If you click it in the editor, it's not going to do anything. But if you want to test it out, just go to file build and then build it for whatever platform you want to test it on and just make sure that that button works in the actual thing. So for opening a load game menu, we're going Teoh either want to activate a menu object that's already an hour seen or two. And Stan, she ate an object from a prefab, which basically means we have the settings for that object inside of our assets folder and that we just basically create a copy of that and the actual scene. So how you gonna actually do it is kind of up to you, but to keep it simple, I'm just going to do public game object on. We'll call this load game menu. So what was set of reference to this inside of the Inspector for the main menu. And then we're going to take that lewd game menu object, and we're going to set it to be active and by setting it to be active. If it's a U I panel, it's going to show up, which is pretty much what we want. We want to open the menu. Eso That's as simple as we could possibly make this script for right now. Now what we need to do back in the Inspector, where we have the main menu and the main menu Monnet Behavior script attached as we need to set the values for those objects. So I'm going to drag this new game button, the load game button and the exit game button into the respective spots. I'm gonna call the new game Seen name, Level one. Make it very simple. The Load game menu we haven't created yet. So we can do that by creating another You I object, so I'll just create a panel here and we'll call it Load game menu. Now, obviously, just like the main menu, you're gonna want to add a bunch more stuff to this, like Gridley outs and titles. But for right now, we're just make it very simplistic. So I'm gonna change the color just so we know that that is different. And I'm going to set that game, object to inactive so that by default, when we're in the main menu screen, it doesn't have a load game. Mitton, you open. And now we can set that load game in years of reference here, So I'm gonna drag the game object for their load game menu. Just so you know, if you don't already realize Game Object can basically be anything in your hierarchy or any pre fab that you have in your Assets folder. And if you ever want to create a prefab, then you just drag one off your game objects into the pre fabs folder, and it'll copy all of the values into here. So now I could create copies of the slowed game menu anywhere I want, which is pretty handy, actually. So one more thing to realize is that as it stands right now, thes buttons are actually gonna have their own click functionality yet because we haven't set the delegate methods, says I mentioned before, you don't necessarily have to reference the buttons in the script. What we could do is have the buttons reference reference the script itself. So just to quickly demonstrate that way of doing it, I'm gonna drag in this main menu object and we'll say runtime only for when the function well done. But we go to the main menu and we do new game here. So now when this button is clicked, it's gonna call the new game function from the main menu. So that's one easy way to do it. But if you want to do it in script instead, then what we can do is call public void awake. And for each of these new game buttons, we need to set their functionality. So new game button dot on click Add listener, and then we pass in the name of the methods. So New Game and that's really all there is to it. So we need to do the same thing for the other buttons. So load button dot on click that ad listener and will say open elude game menu and then exit game button on click Add Listener except Game. And now, when this script awakens, or basically when it exists in the scene, whether or not it's the object to set toe active. That method is gonna be called, and these buttons, they're going to get there on click listeners now. It might be a good idea as well to do some error checking so you could make sure that the new game buttons are actually exist. And they're not know before you try to set listeners to them or else you'll run into errors and real time. Um, so you could do something. Like If New Game Button is not know, then you add the listener else, right? Some debunk message to the council, letting you know that it doesn't have a button set up. Here's a reference, but for right now, those buttons should work. So let's go ahead and hit play so we can test our buttons. Now, for instance, load game. You can see when I hit load game. It sets the load game menu to be active. Now there's nothing on it yet. It's a pretty lame menu, but the load game button does, in fact work. Now, in order to close that menu out, you probably want another button inside of that menu for, like an X button to close the menu. um, but right now we know that works. Now the new game button won't work because we don't have an actual scene named Level One. So you see, when we had new game, it says, Seen never one couldn't be loaded because it hasn't been added. Basically, it doesn't exist. Aan den the exit game bunten isn't gonna work simply because we're working in the editor, but it is being called. We can actually add a debug message just to prove that it's being called. So we could say debug dot log trying to exit game doesn't work an editor. So let's just that out one more time just to show that it is being caught. Okay, so you can see trying to exit Game doesn't work. An editor. Oh, and by the way, a open, safe game button would work exactly the same as the salud game button you could just on a different menu. You probably wouldn't have it in the main menu because you're not saving a game there. You are trying to start a game, but you could just have safe game menu Dotson active True, but that would probably be from a different scene inside of the game. Or, if you got to a save point, that kind of thing 30. How to Make Load Menu Popup & Close Menu Buttons: So for this tutorial, let's just do a little bit more. For one thing, I'm going to take the load game menu, and I'm gonna set that to be not transparent at all. I'm also going to add some padding to all sides and we'll add in a title panel. So if I click panel and then make sure that this is centered and stretched on the top, I'm going to decrease the height. And then let's add a title text. They're calling it Lewd Game, and we'll also add in a button for closing the panel. So I'm gonna put this button in the top right hand corner, and you could change the image if you want more fancy looking button for closing it. But if you just want a really simple prototype of the next boat, and you can just go to the text as a child element under the button and change the text, Teoh acts. You can also send it to Becks best fit so that it is going to be a little bit bigger. Now we're gonna want to take this button and somehow once again, either through script or you can directly attach the method right here. We're going to want to close the load game menu. So I'm gonna actually reference the load game menu object here. I'm gonna drag this down below, and I'm going to take the game object that that's set to, and I'm gonna set it to not be active. So we're taking the load game menu object, and we're calling the game object that set active method and making it set to an active, which is exactly the opposite of what we're doing here with this open load game menu script . Now to show why pre fabs of powerful we did already create a load game menu prefab, but now has extra stuff associated with it. And if we ever want to call a load game menu from anywhere else in the game, we don't want to recreate it every time that we need a load game menu. So what we can dio is we can basically update the prefab. So the quickest way to do that if it if it's like blue here, that means it's attached to a prefab, and we can update the prefab with all of the values off the objects that are nested under it simply by hitting prefab over here. So now this load game menu prefab has the panel, the text, the button and the buttons text all associated with it. And we can add it to a game anywhere we want exactly how it is right now, but, yeah, make sure it's actually in Stan sheeted onto the canvas or it's not gonna render properly. So you can see now we have a second load game menu, which is exactly the same as the first you can see if I enable either of them that they're exactly the same. So if you haven't gotten too used to prefects, I really recommend you start working around with them because they'll make your life a lot easier. Okay, so we can delete this extra game object from the hierarchy. We don't need it in the scene. Now let's just go ahead and test the load game menu and the button one more time. So we're gonna hit play. We're gonna get the load game menu to pop up, and I'm gonna hit the X button to close that menu, and we can keep cycling between them. So now we have a working new game menu. There's a new game button, a load game button and exit game. But now the load game. Obviously, you can't learn the game yet. There's a lot more coating that needs to go into that. But we have the basic framework for our menu at this point. Now, one last thing I want to do with this video is to create a new scene, and we're gonna call this the level one scene just so that that new game button has something to actually load into, Basically proof of concept here. So I'm gonna play on our sample scene and I'm gonna hit new game. And what happens? What happens is we get a ever because that scene hasn't been included in the build setting . So ah, in order to do that, we could drag this scene into the hierarchy and set it to unload seen, um, and I think that should work. As long as it's in the hierarchy, it'll be referenced. But we can go to file build settings and add open scenes to make sure that that scene is gonna be included in the bill. When we actually export our game to the different devices that can play it. So, yeah, if you're ever wondering why you're seeing, can't load, make sure it's and scenes and build here. But now that it's there, I don't think we even need to have it in the scene. I don't even think we need to have it in the hierarchy and anymore. We just need to reference it at least that once. So let's save the scene one more time. Hit, play and trade ahead that new game button and we had new game and it loads suffer one, which has absolutely nothing in it except for a camera with a blue background. But we can tell pretty easily that that's different than this one. Uh, because this one has the canvas on it. I guess the camera color is actually the same blue background. You can change that, by the way, if you want. But that's the basics of how you create a main menu screen from a technical standpoint, and the future will talk more about how to have saved game screens and load game screens that are fully functional, with saving and noting all the data. But for right now, that's gonna be it. for this tutorial. So I've been Chris. Thanks for watching, and I will see you guys in my future unity content. 31. Pause Menu with Prefabs & Singleton Menu Manager Script [Part 1] Setup: Hello, everybody closer. And in this video, I'm gonna be showing you guys how we can create a pause menu for any level off our game and to make things a little bit different this time, I'm going to be in Stan Shih ating the menu as a prefab rather than having it set as object that's in the hierarchy by default. So, in other words, we're not gonna be putting the A menu inside off the scene directly inside of a canvas. But we're actually going to use a manager script that will create an order to Instead, she ate that menu on demand from our prefab, which we have stored, and the assets. So I think this should be quite in depth and probably will be across a few videos. But hopefully you guys will learn a lot from it now before we can. Instead, she ate a prefab. We, of course, have to create it, so I'm going to create a new panel and side of the scene hierarchy, and this is just temporary. Of course, we're going to be removing it from the hierarchy and storing it only as a prefab, and our assets slash pre fabs folder. But right now we have this panel which automatically assigns a new canvas when one does not exist inside of the sink. So I'm also going to assume that you don't want your new pop up menu to take the four game screen. So one way that you can control it sizing would be to have it stretch, but then to give it padding, but then to give it margins on each side. So if we give it a margin of 100 pixels on all directions, or maybe just 50 for the top and bottom When we're working at such a low resolution, we can have it stretched to most of the screen. But leave a little bit off our game, hiding behind it. So next I'm gonna rename this panel to pause menu to Better to find what it actually is supposed to do, and that will add a couple more. You I components to this so I'll create panel here and I'll drag this panel to the top, and I can drag the margin for this panel up towards the top so that it only takes this little top sliver and under that I can add in a text component for a title for this window , and we can say this is pause and all caps and center it so that it's very clear that the game is paused. It also increased the size or check best fit in order to make better use of that space. That's up there, and we can rename this panel to be top bar Now, inside of this pause menu, I'm going to also want to create a new empty. And with this empty, we're going to call this the layout scheme, and the only purpose of this is to organize our budging components that will go beneath it . So an ad component I can type in, uh, let's see layout and we'll do a vertical layout group. So now, as we add new buttons to this layout scheme, it's going to be ordering them in terms of the space available with its parent component. And you can see here the bounce off the parent, which we probably actually want to stretch at least horizontally and probably expanded space to make up the full use of everything beneath the top part. Now we can just duplicate a few more buttons here, making sure that the parent is the layout scheme and the layout scheme will take care of determining where they should go. A couple options you can control here. Arthuis Child Force Expand, which will remove some of that spacing between them. But if you want to set a specific amount of space, you can do that with spacing and was set the child alignment to be upper center and add 25 pixels padding on all directions just to make it look a little nicer. Now, another thing we're gonna want for the top bar is going to be a closed window. But in a way, resume game button. You can determine for yourself how you want this to be placed, but I'm going to just put it as X and the top right hand corner over here and for the text . I'll change that toe X. You could also change the image on the button component itself if you want something looking a lot nicer than just a little piece of text there. But that will serve for right now. Another little piece of information we can add to the pas man, you might be a text that tells the player that tells the player that they can hit X or escape to resume, and we'll stretch that horizontally as well anchored to the bottom. Of course, if you have this situation where your backgrounds kind of dark, it's probably better to change the color too white, for instance. And if you have any other fonts in your project like Kenny Bolt, you can change to that if you think that looks nicer than the default area. For the record, the Kinney Font Pack is actually free to use CC's there a license, that belief. So if you want to take a look at that for kind of more gamey looking funds, definitely Google search that, and you should be able to find it pretty easily. Also, center this text element horizontally, and that makes it a little bit more clear. So let's label what these buttons actually do, both in the hierarchy and the text component itself. So the first button is going to be, let's just say save game. We won't actually write a safe game script in this video, but we'll have it. There is a place order so the next one will be, Um, you could say hence that's something I see some games do where they might have like, hence menu there, of course Hence can also spoil the game. But, you know, it's one option tohave and then, of course, quit two main menu. And what this budget will do is basically go back to our default seen. Currently, it's got sample scene and my photos here, but I'm gonna be named that two main menu to make it a lot more clear. So let's rename these buttons in the hierarchy as well. So I will call this button quit, too. Main menu This one will be but in hence, and this run would be button save game. Okay, so now we can save this entire pas menu as a prefab. I'm gonna drag that into our hierarchy, and I'm gonna delete it from the scene. 32. Pause Menu Prefab & Menu Manager [Part 2] MonoBehaviour Manager Script: So the goal here is going to be to create the pause menu inside of our game when we need it without actually hard storing it inside of the scene hierarchy. So it will always be in our pre fabs, and we just load it when we need it. So to do that will need some kind of seen manager script eso in my scripts folder here. I'm gonna create a new C sharp script. And I would call this game seen Manager to differentiate it from the default seen manager in Unity. There is a scene manager, which is for switching between scenes. But this is more about controlling the behaviors inside of the scenes, like being able to open the menu. You can call it whatever you want, and you can define extra functionality that it can do in the future. Of course. So I'm gonna open this up for editing inside a visual studio code. You can use whichever editor you want. So inside of the game scene and manager script, I'll leave it a mono behavior as well. So for the sake of this video and keeping two core unity classes, I'm gonna leave it as a model behavior. If you look into Singleton design, something like this might make more sense is a singleton which always exists inside of the scene and will be created on demand if it does not already exist. But for right now, what we need to get reference to is going to be a prefab. So I'm gonna call this game object. Ah, pause Menu free Fab and will define this inside of the hierarchy. We just have to have a space here for the prefab. And what we will do here is create a method and we'll call this public avoid open pause menu. So the idea here is that our prefab does not exist inside the scene or we don't expect it to be, at least So what we're going to want to do here is in Stan. She ate the pause menu Prefab, if no instance of it currently exists, so I'm going to call. Instead, she ate, which is a default method to Romano behaviors on the positive menu prefab. And we want to put this on the canvas. So if canvas doesn't exist, then we want to create that canvas. And if it does exist then we want to put this onto the cameras. So one way we can do this is also get a public, actually probably a private canvas. We don't really want anyone setting this manually in the Inspector and all you will call this canvas. So this canvas, that's what we want to use is the transform location for this method. So what we're doing here is we're creating a copy of the game object prefab on top of the canvas transform. And when you attach a child to apparent that means in the hierarchy, it's going to be one level below it. So by doing this, the game object will be created on the canvas, and it will draw on the screen properly. So you should do that for you, I elements. But we should only be doing this if one does not already exist. So if, um, pause Menu instance is equal to know, then we should do that. Otherwise, we should simply tell the current Pause menu instance to be so active to true. So sets well, it's not gonna show the method until we actually define it. So game object pause. Menu instance. Okay, so now we should be able to call the dot set active and something to true. So this game code is first checking to see if one exists. And if it doesn't, then it creates a new game menu. And if it does exist, then set currently existing positive in you two. True. But we so need to do one thing for this simple script to work, which is to do a on awake method for the model behavior. And we need to find the canvas inside of the same. So the canvas is going to be get component in the scene canvass. So if one over the exists, then that gets assigned here, If not then and if not, then we actually wanted to create one. But, you know, I just thought of it even better way to do it. We can do this as a property. So to declare it as a property, we're going to want to defined this again. So call this scene. Canvass said that the name doesn't over ride. So I'm gonna call this scene canvass so that its name doesn't conflict with the class name and we need to do a get and a set. Actually, really We just need get because we're not really trying to create new canvases. So what we'll do is if the current canvas is equal to know, then we will make canvas equals get component canvas. So, basically, if it hasn't been set yet, then we're going to set it with the sing. And if it's still not, um, active, then we're gonna need to create a new canvas element. Eso weaken, Do that s pose within Stan Shih eights. I'm gonna in Stan. She ate a new canvas, and the transform is not gonna be set because we don't want to parent it with anything. We're just gonna create a new canvas. You I component. And then after all of that's done, we want to reach sure in the canvas. And one more thing is to make sure that the canvas very boats actually set there. So this is going Teoh, check if canvas variable this sat then if not set looking scene for canvas and then finally if no canvas in seeing create one and finally we're gonna return the canvas. So with this, I guess we don't need this a week method anymore, at least for the moment, Andi will be able to have a canvas, basically no matter what. So even if we forget to include a canvas and the scene, it's gonna create one force on demand and then threw open pas menu. If we need that canvas on demand, all we need to do is call seen canvas as a property here. So it's gonna go through all this code before returning the final canvas, and then it will give us the transform for that canvas and insane she at the prefab onto that. This is just a kind of more fun, cool way of doing pretty much what we would have done in on awake, which is just to get the canvas in the scene. But it goes one step further and creates the canvas if one does not exist. Okay, so now we need to attach this cool game manager script to a object in our scene. So one place we could port it, assuming you're using the event systems that basically defaulted in everything, we could just attach it to that game object, and it would work pretty much OK, so next I'm gonna drag this pause menu. We created the prefab and to the game seen manager. So now this game seen manager has theme method for opening the pas manure. Instead, she ating and opening it. But it does not actually have anything referencing that script in order to call that method . So there's a few ways we could do it Now. One is just to check if the escape button is pressed and, if so, open the palace menu, which is probably what we're going to do. For starters, another way is that you can't have an event trigger in your game like you go up to a safe point hit, enter checks if there's a trigger collision with that safe point, and then if there is, then you open up a menu, basically referenced the game, seen manager and then call Pause Menu open. So getting that event in game method to work is a little bit more involved, so that will be a different mini video, Siri's. But for right now, we can make it really easy honest by just having it trigger when the escape button is pressed. So a generally better practice would be to separate the import script or import manager from something like a game seen manager. But what I will do just here for this video is I'm going, Teoh make an update method. So we're just kind of include that basic functionality for this game Seen manager in here. But it's up to you if you want to separate it later on into separate scripts and make any everything and to decouple everything from different systems so we can do public void update, which exists in all model behaviors. And what we would do is if input dot get key down is equal to the key code dot escape key. Then we know that import key is down, and now we can call the open pause menu function. Okay, so let's go ahead and actually test this out to see if it works. Okay, So in game stuff's happening, I'm gonna hit escape. And what happens? We get a no reference exception. Okay, I'm gonna check that error and see where it was. I'm guessing it was related to the canvas. Okay, So to correct a couple things in the scene where it says get component canvas, this is actually checking on the current game object, which and this case is the event system. So there was a canvas in the scene, but it wasn't able to find it. So the method we're actually trying to call is find object of type canvas. So if it finds a canvas object in the scene, it will assign it there. Now for this instance she ate. You can't in san. She ate a new game object as a component there. So another way we could do this. And I think this is probably the better way would be to do a prefab as well, rather than manually creating a new game, object with something like Game object and stand she and then adding components like the canvas to it manually. Why not just have it all saved us a prefab with all of the settings we want inside of our Assets folder, just like with the PAS menu. So for that, I would do public game object canvas prefab and instead will just simply be creating a copy of that canvas prefab. And then we'll get component canvas on top of it because the variable canvases storing a reference to the component, not the game object. So the components or what's attached to the game object. So now we can take this canvas, make it into a prefab by dragging it down below one saw unity updates here. So I'm going to create that prefab down here in my pre fabs folder and to prove that everything works, I'm gonna delete that canvas as well. And I'm gonna set it as a prefab that's attached to this gain seen manager script. So now if we hit play, we contest. If the canvas and the positive you will be created on demand. So I'm gonna hit escape and Oh, look at that. So we have canvas cologne and Pause Menu Clone created here a za concede The PAS menu is attached to the clone and we have all of the buttons, the text and the close menu button up here exactly as we created it in the prefab. So using prefects, you can accomplish a lot, especially if you need to duplicate enemies or things of that nature. Pre fabs become very, very useful. Now I am back out of the game run time and we're just working in the hierarchy again. So we start to do a few things here. We have a pause menu that can open, but none of its buttons actually do anything at the moment. So we need to create a script for the PAS menu and probably attach it as a model behavior on the PAS menu itself. So let's go to scripts, and I'm going to create a new script, and we will call it a pause menu. So this time I'm not going to be keeping a reference to the buttons inside of the script. But rather, the buttons are going to reference the script inside of the inspector, where you can set on click delegates straight in the inspector, which is great for designers. You don't have to worry about code, so we just need to create the methods which this process menu is capable of doing. So let's start with a close menu button, and this is going to take the game object and set active and false. Now, another alternative. If you want to destroy the prefab sorts not and you're seeing when it's not being active, then another thing you could do as an alternative is destroy this dot game object. Okay, so when you say this, you're referencing this script but you actually want to reference the game object that it's attached to. So we're gonna be attaching the PAS manuscript to the possum in your game object. But we don't want to destroy the script because then the rest of the pause menu everything but the script functionality is still gonna be there. That's where you need to call this stock game object. Not this a pretty common mistake there. Next up will do open save menu and just for fun, because we're doing it. The prefab method Rickard put in a public game object save menu prefab here. And then we'll create that. And it's the exact same thing. Is the game seen manager? We just want to open that Ah, safe manure. So I'm gonna run this over here. So the next thing that we would need to be able to do is to create a open save menu function so that the button inside of the pas man, you can call that. So as things are here, we could be valued basically the open past menu function. We re write the same thing here, and we could also reveal ate the same code where we get reference to the canvas, just like in the game seen Manager. But we don't actually want to have to be right code over and over again and make things messy anyway, now, because the PAS menu is not actually going to be inside of the scene when the seen loads, it's unstamped sheeted from a prefab where the safe menu as well, we can't actually reference that script at the moment by doing something like Game Seen Manager game Seen Manager because it doesn't exist when we're working with the prefab prefab only has knowledge of the components that are under it now. We also can't just simply make the game seen manager a static class like this, because inherits from Mona behavior. So what we actually want to do here is to turn the game seen manager into a single 10 and when it's a singleton, it'll be able to be referenced statically from other scripts like this so we'd be able to call something like game seen manager dot whatever method we have in there. But you can see those methods they need to be static or we need to have a reference to the actual game manager instance. So in the next video, we're going to be talking about a really cool library called Yeah Singleton and will actually be churning this game. Seen manager from AMANO behavior into a Singleton instance, which still has a model behavior functionality. Basically, um, and it actually goes a step further than that because will be up to create this game, seen manager as a file that exist inside of our Assets folder. So the game seen manager will become something that always exists. They'll always be one copy of it, and we can reference it from other scripts like this Pause menu, even if the Pause menu is not going to exist when the game starts but rather be in San Sheeted as a prefab. And what you might notice is that going this direction with Singleton systems that exist one off in your system is actually a bit more similar to what unity's coming out in the future, which is the unity. Each CS or entity component system now for now, will be using Singleton's E. C. S. It's nowhere near ready for the public yet, and this reserve is a cool way to get these global scripts running that we can use inside of our of the game objects are you I components and basically be able to reference their functionality on demand and be sure that it always actually exists. One copy of inside of harassing eso. Anyway, that's gonna be the next video. For now, that's gonna be it. So I've been Chris. Thanks for watching. And I'll see you when we continue working on these pas Manu scripts inside off unity. 33. Menu Prefabs & Menu Manager [Part 3] Singleton System : Hello, everybody. Chris here. And in this video, we're going to continue working on our palace menu script by turning it into a single 10 objects. So if you're not familiar with the Singleton design pattern, it's where you would have one item inside of a scene that spawned from a class. So basically, whenever you have a single 10 you can only create one off in your scene, and it should be able to be statically referenced, usually by the name of the class. Dot instance. And then you referenced whatever methods you want in it. So using a library like, Yeah, Singleton, which implements that design pattern, works out really well for us when we want something like a system which should be global, stay in this scene, possibly transition between scenes and still be there but gives us the ability to have global functionality that we could easily reference in other scripts and knowing that no matter what, because we're statically referencing that class, it's going to be talking about the same object at all times from all scripts. So if you go into the Unity Asset Store, you can search for yes, Singleton, which, as it conceives a free ad on, um, just by typing in Yes, single 10. It will be the 1st 1 in there, and way just means yet another singleton the library. And so we can import that into our project. You don't need the examples unless you don't want it to be there. Just everything under the yes Singleton folder. Import that. Okay, so now that we have this in a photo in our project, if you wanna pop that into a plug INS folder, I guess we can do that Kind of makes sense. So I'll create a folder called Plug Ins and we will drop Yeah, Singleton into that just for better organization. But now we can edit any model behavior script and turn it into a singleton object. Okay? So earlier, I actually meant we were going to take the game seen manager script and turned that into a singleton object. Ah, the pas menu. If we have a pause menu script at all that will still be attached to the prefab where we have a pas menu prefab. But for this game, seen manager, anything that's a manager's is going to be something that we want to have a global presence within the game, so it's a perfect case for using Singleton. So to use the Singleton package, all we need to do is change it from amount of behavior into a singleton of the type of the class. So if we have public class game seen manager than its single 10 game seen manager. So we're basically wrapping our class inside of a single 10 object here and we can import that using yeah, Singleton s own. At this point, this class, whenever we have inside the game, it should only be able to have one instance of the game seen manager, and we should be able to statically reference it. So how the Singleton Library here works is that all of these script herbal objects, meaning you can create an instance of them inside of our game. Resource is the assets folder, though I'll be collected and managed inside of the Singleton update. Our script, which loads win the game loads So the singleton updated will pick up all of our single 10 classes all the instances of those classes, and load them with that helper script. So by having that helper class, it's able to pick up on all of the script herbal objects and allow them to run their game functionality without themselves, actually, technically being modeled behaviors and because they managed by the Singleton updated, you also able to call stuff like on update Inside of a Singleton objects. So now, just to show if we dive into Singleton in and based Singleton, that's where you can see that it is a script herbal object. So being the game seen Manager is now a script herbal object. We can actually put in an attribute here so that it can be created as an asset inside of our project, and it will automatically be picked up on by the Singleton update or without us having to actually attach it to your game object in the scene. So to do that, we use the Create Asset menu attributes, which will take I believe it's file name and we will set that string to be game seen manager and menu name will be the path and the name of this Create assets menu function in the right click and appear at game object. I think it's a game, object or component. It will show up here for us to be able to call that function and actually create the game. Asset s So let me show you what I mean. Here, we're going to call this systems as a path and then game scene manager, which means it's going to be added in ah menu folder called Systems. And then under that is going to be game seen manager. So as long as we save this, we should be able to see the create asset menu function back inside of unity. So if I right click here after everything compiles and we go to create, you can see this new menu item called Systems and as game seen manager under it. So by using that right click menu going up to assets create systems, we can now create an instance of that game seen manager to store inside of our project, much like a prefab would. But I'm going to create this in a folder called Resource Is I believe that's the standard way to do it. And in this I don't know, we'll make another folder, will call it systems, just kind of organizing everything here and inside of here will actually run that function . So create systems game seen manager and oh, look at that. Now we have a game seen manager inside of our project. You can see that it still takes references to the pause menu, Prefab in the canvas prefab. And if we hit play to load the game. Uh, this game seen Manager should show up in Don't delete on scene load. So let's see or don't destroy on load and you can see it's being managed by the Singleton Update ER, and we can see all of our singleton objects automatically populate in here. So this is really cool. Any kind of system you want to have inside of your game, something that should always exist. You can just create a singleton object for it, and it'll automatically load with your game. You don't have to attach it to anything in the hierarchy. Any mode Singleton updated will automatically be insane. She hated assed long as you have that plug in inside of your project. So this is really, really cool, and hopefully in future videos, I'll show you guys a lot more that we can do with this as well. So for now, you probably want to actually change this game. Seen manager to have the default set so we can go grab the pre fabs. So let's see the Powers Menu, prefab and the canvas prefab. And if we get rid of the canvas inside of the scene and hit play, we should be able to use this game. Seen manager in the same way pretty much that it worked when we had it attached. Teoh a script. So let's see. Escape your, uh But, uh, whenever we're running into, we do need to make sure that game seen managers no longer attached to events, system or anything else in the scene because it's no longer amount of behaviour, which means you can't attach it to anything. It's a script herbal object. Eso Let's see events, systems, game seen manager. Yeah, OK, so we should remove that. And now we can go ahead and hit play and it should work properly now, OK, it's playing. Looks like no more errors and we hit escape, and it's now actually taking the escape function. So let's go back in the code and see what went wrong here. Okay, so, um, the thing is, update no longer exists. Remember, This is a script herbal object now, but because this actually gets added onto Singleton updated, which is an executor, behavior basically functions like a mono behavior for our purposes. What we call instead of update is on update, and that's always should have to do OK, it should be public override on update. If you want to see any of the other functions that exist for these Singleton's, you can just right click and go to definition and go to base Singleton definition, and you can see these functions you can hook onto inside of the unity lifecycle. So on fixed update if you're doing physics on update on late update, if you need something to happen after on update and you have several other methods there and you can also do an override of on initialized, which, of course, you're gonna want to do based on updates that this gets called still so that the Singleton Update er actually grabs this Singleton Ah and D initialized where you can have stuff happen when this singleton object is no longer being used. But for now, public override void on update and whatever code you wanted to run and we can go ahead and hit play. Now we had escape and look at that. The PAS menus being in Stan Shih ated from our script Herbal Object, which is a singleton and only one will exist inside of the game. And the reason would doing all of this is that now that we know this game seen Manager is an object which will always have an instance of it. As long as you've created the script herbal object, then we can just reference game seen managers. Instance, Any time we want to get anything off of this game, seen managers such as a reference to the canvas prefab or the PAS menu prefab. So that's gonna help us out a lot when we're trying to reference it without actually seeing it inside of the hierarchy. So, like, if you have to reference a game, object directly that's inside your hierarchy. It needs to be put there before the scene exists. But if we can just call the class dot instance than as long as there's an instance inside of our currently running game, it will get reference to that. So in the next video, we'll be working on the PAS menu and probably change around a little bit of the code in the game. Seen manager changing this to be more like open menu that we can call on any game object that is a menu and in the end will be able to have the PAS menu open up this safe menu and probably implement some more menu based functionality there. So until the next video, I've been Chris, thanks for watching, and I will see you in my next unity video. 34. Menu Prefabs & Manager [Part 4] Decoupling Data from Singleton System: Okay, So in this video, we're going to be working with our PAS menu and thesis. Ingle 10 games seen manager. By the end of this video, I think we're going to be taking much of thes functionality, like opening a menu and closing a menu. And we'll be able to actually just straight up take it out of this class and rather have most of our functionality go with the system or the manager. Whatever you wanna call it. Ah, where the code that actually executes will exist here. So for that reason, which is gonna make the game seen Manager changed to Menu Manager because we really only want this class to be for this specific function. So menu manager, just make sure that wherever there's a reference to that name, we change it. Here s O many manager and all those forced spaces and the nebula file as well. And we will change this open possum in you to open menu. And in order to open a menu, we need to know which game object we are referencing. So game, object menu prefab. Yeah, and we can actually call this more like create menu now, whether it makes sense to you to actually have the menus exist inside of your seen all the time on a canvas that is set up in the hierarchy Or if you want to create them on demand within Stan Shih ation. Ah, that's up to you for right now. I'm just gonna keep it. As in Stan, she ate because that's what we were doing in the last couple of videos. Um, so we need to create a menu from a menu prefab. So we'll take this parameter and make it in Stan. She ate that menu. Prefab at the scene canvass dot transform, um, and since will be creating and leading menus on demand, I'll just get rid of this part because the idea here is gonna be m always gonna destroy those menus. So also want a public void destroy menu, which will have a reference to a menu mono behavior sokol this menu menu and will create this menu class. We can actually just go ahead and do that here, So I will. So this name actually conflicts with something in the unity editor so we could call this something else like game menu just to keep it be two separate names. And then we can generate this in a new file, which will be created inside of the same directory as long as we're using visual studio code. And so this is going to be a mono behavior, which should be attached to every game menu prefab. So let's import that from Unity engine there, and we'll worry about what this actually don't sit him in a minute. So now for destroying menu will check. If menu does not. You go? No. Then we'll destroy menu Dark Game object. And we could actually have the menu manager maintain a list of these menu game objects if there's more than one on the screen. So I guess we call this list whips list of, uh, game menu, and we call this active in years Now. We're gonna want this active menus to be fresh every time this menu manager and Stan Shih eights itself so we can overwrite over at the initialized method. Um, so that's going to be private or no, no protected. Sorry, And then the return type is avoid and we do based start initialize here to make sure it gets added to the Singleton update ER and now we consider active been used to a new list of a game menu. So something I'm not 100% sure on here is if we can reference a prefab as the script that's attached to that prefab. So instead of passing in a game object menu prefab both in The Inspector and down here, can we just reference that's a public game menu? And then we'll call this menu prefab, and then we'll call this pause menu free Fab to, um, actually would just we'll call this pause menu prefab and comment out the game object version of that and that will pass in game menu over here, then menu, then for open PAS menu. Instead, we just want to open the prefab. So would do create menu here, and we're used the prefab. So now we want to actually insane sheet the menu dot game object. So when a few reference a prefab and the editor when the game actually loads, it becomes its own game object. So in theory, this game menu script should be attached to its own game object, and we should be able to instance she ate a copy of that game object with this? And Stan, she ate method. Um, so we have to see if that's actually gonna work them now for future reference. We want to be able to keep track of all of the active menus. So as we create this game object new menu. We also want Teoh. Add that to the active menu. So I'll do a new menu, and we'll get component on that, which is gonna be the game menu. So this is the new instance of the game menu script on the new instance of the game object . And when we destroyed the menu, we also want to remove it from the active menu. So active menus dot remove menu removing it from the list, and then we destroyed the game object. So by doing this, uh, this active menus list should contain all the references to the active menus as long as we always remember to call, create menu and destroy a menu, Um, when we're loading and unloading our game menus. So with that, let's do a little testing back in the editor. So we have this menu manager and it is a script herbal objects. So we go back over to R V Sources Systems folder and we find the object. And now we're looking for the positive in you prefab. So this proximity free fab as it stands right now should be a game menu, not an actual prefab. So let's see what happens when we actually change that pause menu prefab and it's still there. Let's try that one more time cause menu prefab. Uh, okay, um, you know what the problem is? We change the name of the class, so the actual script herbal object is lost reference to it that is one down side of having the script Herbal objects to be careful about that, if you change the class name, you might need to be create your object or at least re reference the script there. So I'm gonna just recreate the object to be a little quicker. And let's try getting a reference to that pause menu. Okay, so that doesn't actually work. We do need to reference the game object itself. Okay, so given that that's the case, we'll have game object pas, menu, prefab and all that will need to change here is that when we're calling a method on it like creating the menu. We just need to get the component out of that prefab. And we should also make sure that that actually exists the components. So we're going to call this. So in the on update code, we're gonna call game Menu menu equals the prefab dot get component, uh, game menu. And if menu does not equal no, then we will create the menu. With that, we can move this comment up here, so create the menu with some menu otherwise reassured. Log in error. So debug log error pas menu Prefab has no game menu script attached to it and get component . You also have to put the little parentheses there because it is calling a method. Okay, great. So now we can attach the pause menu prefab here. Now, if we run the game as is, it's gonna error out because this pause menu prefab does not have the script attached to it , hence writing this debunk message coat. So let's actually just go ahead and test it out in game. When I hit escape, we should get an error. So I had escaped and look, we get the Eric because this no script attached to it. So we need that script attached because the menu is going to contain some references. Hopefully. So at this point, what the menu will be responsible for is containing probably mostly references to the button variables. And that's what thing on baby. Some properties as well. But most of the code will actually be run in this menu manager. But let's just attach the script to that prefab. So we're going to call the game menu script, and obviously there's nothing on it yet. But as we add stuff to it, we want to make sure that it is actually already loaded in there. So So let's play it now hit, escape and it's loading again. Now the close button doesn't work at all right now, because we're not using the PAS manuscript anymore. I'm not even sure we need this close menu function here because I think game objects can just call this directly so we'll actually see by basically going into this prefab okay, and we'll need a in the hierarchy temporarily, but will go into the prefab and find the close menu button, which I will rename Menu Button and let's see if we could just add the on click event directly here. So pas menu being referenced there and we'll go into functions. Game object. Okay, so it has set active, but it doesn't have destroyed, so there's a few different ways we could go about it. Here. We could add the close menu method into the game menu script, which would be pretty much how we had it in the two videos ago. Could also just have a called game object outside active and will make that not active. And then, in our Menu Manager script, we could just check to see if any of the game menu game objects are inactive. And if so, just destroy them or third option would be. We can take the PAS menu with with the Game menu script and have the stick of reference to our close menu bottom. And then, from there we just call the game Men joined menu Manager, and from there inside of the game manuscript, we will just call menu manager dot instant Stott Destroy menu, and that would be better if we actually want to keep track of all of the's active menus, which I'm honestly not 100% sure if we would need that later on or not. But, um, being able to manage it like this would allow us to play around with these game menus if we haven't needed to change something like, if we I don't know, you needed to change the color of all the game menu simultaneously or something like that. Okay, So for the sake of argument, though, I think what we will go with is that we're going to keep the functionality in the menu manager, and then the game menu will simply contain a reference to the button. And as we create a new menu, as long as the menu manager exists, it's gonna add onto that button the functionality where, when it's clicked, it's going to destroy the menu. 35. Menu Prefabs & Singleton Manager Part 5 Control UI Menus in Singleton System Code: so to do that and game menu, we should have a public button destroy menu button. And we can, of course, get that lower case because it's not a property. And we're gonna be using unity Engine. You I for that. So that's all having this script for right now, and that will go back over here. So when we create the new menu, we're gonna get reference to the game menu, which we already dead. But we're just gonna cut this code out here so we could do a little bit more on it. And then when we're finished doing more stuff, well, add it into the menu. But for right now we want to assign functionality to the buttons. So what we'll do is menu dot destroy menu button, and we'll do the on click event at a listener so we can add a unity action, and that will be to destroy the menu of the menu itself. So we finished that up. It should work there cannot convert from void Teoh Unity events action. So normally, when you do add listener, you could just directly reference a zero argument method. But we actually need a argument here which is the game menu. So what we can do here is change this code up a little bit and said we're going to be creating a delegate here. So this is gonna be a delegate of the method and by typing it like this, were actually able to pass in the parameter. So if you ever run into adding a listener for on click event and you need it, just wrap it in a delegate and pass it. And it's the argument for the ad listener method. Um, no. Let's see here menu dot came object. Okay. Okay, So this naming is actually a problem because we passed in menu over here. So? So we need to change this to some kind of new name. Let's go with menu component, I suppose, and will update the references to make sure we don't have anything going on with that menu up there. We only want the menu as the argument to be the thing we and Stan she ate from. So let's see, many component. Okay, we get the destroyed button, we add the listener, which is going to destroy the menu of the menu component which should get the game object and destroy the game object. Also removing it from the list. So I think we're actually good here. In theory, this should work, so let's go test it out. Of course. Okay, so back in the unity editor to test this out, let's actually set a menu button here. So the menu button is obviously gonna be inside of the prefab a song. As we're working with the prefab, you can just dragon dropped references to other game objects inside of it. Because this prefab is gonna be insane. Sheeted. Always one thing. So it's always gonna have a reference to this. So dragging that in here, we'll work pretty easily. So we apply that to save it to the prefab. Let's delete it from the scene. Hierarchy hit, play and test things out. No errors in the console had escaped to open the menu. And now, if we left click this assured, close the menu. Awesome. So now we have the functionality of these menus being set without even having anything. Go on inside of the game. When you the game and you just contains a reference to the button and doing that sort of thing. We can separate basically our properties from the actual game code, having managers or systems run the coat and then attached to our actual game objects or just basically components that contain a bunch of data or references to variables. And this is kind of going more in the direction of unity E C s, which isn't out yet. But the idea is you would have components rather than mono behaviors, and they can only contain values. So I don't think a budget would technically qualify there. But you would just have, like, floats and billions over and these components and and then all of your actual functionality would be in system scripts. But that won't be out for quite some time now, So don't worry too much about that unless it's something that really interests you. So now one more thing we do need to be able to take care of is to reference the safe menu prefab. So the PAS menu is supposed to be able to open the safe menu as well. Now, I think for right now I'm just gonna take this prefab, cut it out and paste it into the menu manager. We just have the menu manager contain all of the pre fabs for the game. But it will be that buttons on the menus themselves that actually do the opening, but the code will be stored here, so save menu prefab. We can actually just go ahead and delete the pause menu altogether. So I'm going to do that here and now. Whenever we create them in, you will want to somehow check if it's a PAS menu or a safe menu to determine what buttons should be being put onto it. Now, at this point, you could split this up into several different scripts. You could have like a safe menu manager, pause, menu manager, all the other kind of stuff. So for right now, I will do public void on Bill, say inst an she ate pause menu. And then we'll also have public void in Stan. She ate save menu, so what we'll do is we'll check what type of game menu this actually is before we do things like assigning this before we do stuff like assigning menu specific buttons so the PAS menu will have open save menu. But but the save men, you will not have that same functionality, but we don't want to keep retyping this in, Stan. She ate code. So actually, what? Call this more like add pause menu functionality and at save menu functionality. So in order to figure out if we should add process menu functionality or add safe menu functionality to the game menu, we need to check what type of game menu this is actually being. So game and you will actually turn into an abstract class here. So I'm gonna do that now because we don't want this to be its own class that people actually inherit from. We want to add a safe manuscript or pause many script on to three game object. So we're gonna just check if, um menu component doc get type is equal to type of possum menu. And if that's the case, then we'll do something else. If menu component dot get type, you know, this would actually make it a little bit more since if we just wrote it once. So type is menu component doctor type. Okay, so yeah, right once and then just reuse the variable. So type equals pas menu. Okay, great. And let's see else if tape equals type of save menu, and then we'll do that. So great ad safe menu functionality add pause menu functionality. So at least a basic level that seems logical. So let's see. Now, how are we actually going to add that on? Well, first, we going to need reference to that menu component. So to do that, I guess we'll CASS it. So casting it as a positive in you, Um, let's see. Menu component. Does that work? OK, well, is sure. So let's see. Pause menu, uh, pause menu. Okay. Yep, No errors there and then save menu safe menu. Great. So now we can have some custom stuff toe happen when it's a possibility and some custom stuff to happen when it's a safe menu. So for the PAS menu. So this is going to