I vastly prefer your tutorials over other people because you actually explain what the code does which is really helpful for someone new like me. Not to mention you don't show people how to make your game, you instead show a component that is useful for any game.
you are honestly the best at making these tutorials, its so nice seeing someone explain every detail of whats going on. a lot of new people havent even used c# before and its awesome to see you understand that
Great tutorial! You managed to teach a complete newbie who had been awake for two days straight how to do this in a very straightforward and well explained manner. If that isn't some kind of universal seal of approval I really don't know what is. Anyway this part of the code is working great and I'm gonna sleep I think, good night folkes!
You're the best C# Unity tutor I've seen in youtube. I love how you explain every detail very clearly while considering about what the viewer might know and what has to be yet. Also the extra details you give are very helpful and very applicable. Thank you for doing all these nice tutorial!
Great explanation! You are very good at describe why things happen, and why it's wise to do in one way and not the other. Very thankful. Please keep up the good work!! :) Cheers!
Very nice tutorial indeed. I added a minHealth value instead of a hard zero value to check against so that it can be modified by other values that extend it into negative for additional depth of health without necessarily increasing the max outright or even as a higher positive for shallower depth of health alternatively, 😄
Thank you so much! At first I was very confused and skeptical about this system. I did it differently But the longer I use this method, I see more and more advantages. Your tutorials are amazing! You are the best C# Unity teacher! You don't give us fish, you give us fishing rods. Very nice fishing rods xD Can i ask a question? Do you consider doing more Unity tutorials in the future?
I've been looking for performance improvements to my top down and your tutorials have been awesome! I'm hoping in your next one you show how we can instantiate enemies with their own health bars in this system for further improvements. Really love ya work and explanations, thanks heaps!
Thanks man! Appreciate it! I won't be touching upon instantiating enemies and performance in the next video, since videos like these get too long and "out of focus" if I mix multiple concepts into the same tutorial. But I will of course try and show how to create a health bar in a efficient way. 🙂 If you wanna look into performance when instantiating objects, you could look into 'object pooling' if you plan on using the same assets multiple times.
So if I plugin "public UnitHealth _enemyHealth = new UnitHealth(20, 20);" in my enemy health controller script, then how do I make the current and max health changeable through the inspector? The reason is that I am creating a single health script for all enemies and when I add this as a component, I want to change the health according to the enemy, rather than creating multiple UnitHealths in multiple scripts.
Hey Dani, nice tutorial. I just have duplicated your health system and try to convert it (beneath your health system) into a stamina system. But I struggle to change the voids into gaining stamina over time. Can you please make a video for a stamina system, which is similar to your health system?
Awesome tutorial I've been stuck on this awhile! I have a problem though. How do I add damage (hurt) and death animations to my character, I'm confused as to which script to add it to, the unit health or the player behavior health or if I'm supposed to have a separate script for that? If you have a video on this already I cant find it, but you script much differently than most people so I'm having trouble determining where it goes. Any help would be appreciated!
hey dani, thank for the tutorial. i've followed what you did and it worked very well for the player. but when i try to instantiate the class in an enemy script and call the dmgUnit method it doesn't decrease the health, it just stays at the health i've set in the enemy script.
Hard core feel that sigh when at the end when the player didn't take damage bc the player behavior script wasn't on the player game object. 30% of the time is the reason something doesn't work! The other 70% is bc I forgot to save changes...😆
Hmm That’s a really weird way of doing health. I’d make a health component and put it in the player itself, which then invokes events for death and have the game manager subscribe to the players death event?
Hey any idea why im getting the following error when following your scripts exactly? I've double checked them 20 times and cant figure it out NullReferenceException: Object reference not set to an instance of an object PlayerBehaviour.PlayerTakeDmg (System.Int32 dmg) (at Assets/_Scripts/PlayerBehaviour.cs30:) ???
For anyone who is having this problem, it is actually pretty simple to solve. Once you have finished writing the scripts, you have to drag both the PlayerBehaviour script and the GameManager script on the Player and the problem will be solved.
I need help, Whenever I press the keys for taking damage and healing it gives me an error "Object reference not set to an instance of an object" in Player Behavior. How can I get rid of this error?
to anyone who gets this error: You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed. MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all UnityEngine.MonoBehaviour:.ctor () You are not supposed to generate UnitHealts from Monobehaviour. The problem will be solved when you remove the Monobehaviour part in the script🥲
I didn’t do that in the video? 🙂 I just double checked to make sure that I removed the monobehavior from those scripts. Edit: Ah just realised this probably wasn’t a correction to the video hehe. 🙂
How do you do that? If you just delete the :Monobehaviour from the GameManager script, i get other errors like The name 'Destroy' does not exist in the current context [Assembly-CSharp] and highlights the Destroy function from the if statement.
I must have done something wrong, cause I only get an error when I try to run this code: "Object reference not set to an instance of an object". I'm completely new to unity so I got no idea what this means haha, could someone help me out?
It means that your code can't find a object that you are trying to reference. 🙂 So either you forgot to drag a object into your script in the Unity Inspector, or you forgot to add a component to your game object. These are the most common reasons for this error, and all of them are solved inside Unity, and not in your code. If you have double checked the above, then next is to check your code for spelling mistakes and typos. 🙂
@@Dani_Krossing Ooooooh I see yeah that makes sense, however I just can't seem to figure out which object I don't have in the Inspector. Playerbehaviour was the only thing you were supposed to drag in, no? Btw, thanks for such a fast response!
What line does it say the error is on? And can you paste the script the error is in? 🙂 Make sure you check that it is the correct script you paste, that the message says the error is in.
It's a bit late for this reply, but for anybody else who struggled with this, I handled it like so. In the script handling your player object: if (GameManager. gameManager. playerHP. Health
It's way more complicated than any tutorial I've seen. For instance, I'm trying to have the player take damage whevener it collides with an enemy by doing so: void Update() { if(OnCollisionEnter(Collision.gameObject.tag == "Enemy")) { PlayerTakeDmg(1); Debug.Log(GameManager.gameManager._playerHealth.Health); } } But it returns nothing. Is there a simple way to do that?
I noticed that you placed you OnCollisionEnter() inside the Update(), inside an if() statement. Both functions need to be in the scope of the class for it to work, as well as not inside an if() statement. 🙂 Also, yes by making a separate UnitHealth script we make the system slightly more “complex”. But by doing it like this, it becomes much more modular, and reusable in the future. In reality it isn’t really “that complex”, and you’ll notice as you start making games that it is fairly common to separate scripts to make them reusable. 🙂 I’d instead argue that “other tutorials are oversimplifying it”, which makes for bad habits…
I'm struggling with the tutorial; if you could help, it would be very appreciated. So I have two problems: You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed. MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all UnityEngine.MonoBehaviour:.ctor () ^^^ This warning appears without pressing play on the game. 0 UnityEngine.Debug:Log (object) ^^^ Whenever I damage the player or heal, the value is always 0. This is my code. *GameManager.cs*__________________________________________________________________________________________________________ using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameManager : MonoBehaviour {
public static GameManager gameManager { get; private set; } public UnitHealth _playerHealth = new UnitHealth(100, 100);
void Awake() { if (gameManager != null && gameManager != this) { Destroy(this); } else { gameManager = this; } } } *UnitHealth.cs*_______________________________________________________________________________________________________________ using System.Collections; using System.Collections.Generic; using UnityEngine; public class UnitHealth : MonoBehaviour {
// Fields int _currentHealth; int _currentMaxHealth; // Properties public int Health { get { return _currentHealth; } set { _currentHealth = value; } } public int MaxHealth { get { return _currentMaxHealth; } set { _currentMaxHealth = value; } } // Constructor public UnitHealth(int health, int maxHealth) { _currentHealth = health; _currentMaxHealth = maxHealth; } // Methods public void DmgUnit(int dmgAmount) { if (_currentHealth > 0) { _currentHealth -= dmgAmount; } } public void HealUnit(int healAmount) { if (_currentHealth < _currentMaxHealth) { _currentHealth += healAmount; } if (_currentHealth > _currentMaxHealth) { _currentHealth = _currentMaxHealth; } } } *PlayerBehaviour*_________________________________________________________________________________________________ using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerBehaviour : MonoBehaviour { // Start is called before the first frame update void Start() {
} // Update is called once per frame void Update() { if (Input.GetKeyDown(KeyCode.Space)) { PlayerTakeDmg(20); Debug.Log(GameManager.gameManager._playerHealth.Health); } if (Input.GetKeyDown(KeyCode.LeftShift)) { PlayerHeal(10); Debug.Log(GameManager.gameManager._playerHealth.Health); } } private void PlayerTakeDmg(int dmg) { GameManager.gameManager._playerHealth.DmgUnit(dmg); } private void PlayerHeal(int healing) { GameManager.gameManager._playerHealth.HealUnit(healing); } }
@@mysh229 You are not supposed to generate UnitHealts from Monobehaviour. The problem will be solved when you remove the Monobehaviour part in the script
I vastly prefer your tutorials over other people because you actually explain what the code does which is really helpful for someone new like me. Not to mention you don't show people how to make your game, you instead show a component that is useful for any game.
HOW are you not viral yet?? HOW. Hands down outstanding tutorial
you are honestly the best at making these tutorials, its so nice seeing someone explain every detail of whats going on. a lot of new people havent even used c# before and its awesome to see you understand that
Nice tutorial Dani, we really appreciate your work!
Your videos are always well-explained for beginner game developers. So much appreciated! 🥰
Great tutorial! You managed to teach a complete newbie who had been awake for two days straight how to do this in a very straightforward and well explained manner. If that isn't some kind of universal seal of approval I really don't know what is. Anyway this part of the code is working great and I'm gonna sleep I think, good night folkes!
You earned a sub, your videos are always so helpful!
You're the best C# Unity tutor I've seen in youtube. I love how you explain every detail very clearly while considering about what the viewer might know and what has to be yet. Also the extra details you give are very helpful and very applicable. Thank you for doing all these nice tutorial!
Great explanation! You are very good at describe why things happen, and why it's wise to do in one way and not the other. Very thankful. Please keep up the good work!! :)
Cheers!
Thank you for the video!
This is an amazing tutorial!! well explained and easy to understand. Also good practices so you can reuse scripts.
Very nice tutorial indeed. I added a minHealth value instead of a hard zero value to check against so that it can be modified by other values that extend it into negative for additional depth of health without necessarily increasing the max outright or even as a higher positive for shallower depth of health alternatively, 😄
Thank you so much!
At first I was very confused and skeptical about this system. I did it differently
But the longer I use this method, I see more and more advantages.
Your tutorials are amazing! You are the best C# Unity teacher!
You don't give us fish, you give us fishing rods. Very nice fishing rods xD
Can i ask a question? Do you consider doing more Unity tutorials in the future?
Great video! Thanks for the knowledge. I have one question: How would it be to make a bullet, for example, give dmg value to player or enemy?
I've been looking for performance improvements to my top down and your tutorials have been awesome! I'm hoping in your next one you show how we can instantiate enemies with their own health bars in this system for further improvements.
Really love ya work and explanations, thanks heaps!
Thanks man! Appreciate it! I won't be touching upon instantiating enemies and performance in the next video, since videos like these get too long and "out of focus" if I mix multiple concepts into the same tutorial. But I will of course try and show how to create a health bar in a efficient way. 🙂 If you wanna look into performance when instantiating objects, you could look into 'object pooling' if you plan on using the same assets multiple times.
@@Dani_Krossing - no worries, completely understand and thanks for the tip on object pooling for me to look into.
Your doing an awesome job!
So if I plugin "public UnitHealth _enemyHealth = new UnitHealth(20, 20);" in my enemy health controller script, then how do I make the current and max health changeable through the inspector? The reason is that I am creating a single health script for all enemies and when I add this as a component, I want to change the health according to the enemy, rather than creating multiple UnitHealths in multiple scripts.
Is there a video for putting the health system on an enemy im lost trying to to just figure it out.
Hey Dani, nice tutorial. I just have duplicated your health system and try to convert it (beneath your health system) into a stamina system. But I struggle to change the voids into gaining stamina over time. Can you please make a video for a stamina system, which is similar to your health system?
helped so much! sub to this man!
Awesome tutorial I've been stuck on this awhile! I have a problem though. How do I add damage (hurt) and death animations to my character, I'm confused as to which script to add it to, the unit health or the player behavior health or if I'm supposed to have a separate script for that? If you have a video on this already I cant find it, but you script much differently than most people so I'm having trouble determining where it goes. Any help would be appreciated!
Thanks!
Taking a shot every time he says "Particular"!
hey dani, thank for the tutorial. i've followed what you did and it worked very well for the player. but when i try to instantiate the class in an enemy script and call the dmgUnit method it doesn't decrease the health, it just stays at the health i've set in the enemy script.
Hard core feel that sigh when at the end when the player didn't take damage bc the player behavior script wasn't on the player game object. 30% of the time is the reason something doesn't work! The other 70% is bc I forgot to save changes...😆
Hmm That’s a really weird way of doing health. I’d make a health component and put it in the player itself, which then invokes events for death and have the game manager subscribe to the players death event?
Hey any idea why im getting the following error when following your scripts exactly? I've double checked them 20 times and cant figure it out
NullReferenceException: Object reference not set to an instance of an object
PlayerBehaviour.PlayerTakeDmg (System.Int32 dmg) (at Assets/_Scripts/PlayerBehaviour.cs30:)
???
Got the same exact issue, am I on an outed version?
2021.3.something i forgot
For anyone who is having this problem, it is actually pretty simple to solve. Once you have finished writing the scripts, you have to drag both the PlayerBehaviour script and the GameManager script on the Player and the problem will be solved.
idk why but whenever i go to test the keycodes it runs the imput three times?
if anyone has any advice ill take it
I would need to see some code to help 🙂
@@Dani_Krossing already took care of it but thank you for being willing to help
guys I need help, Im at the gamemanager part and it says it wont work because the script class cannot be found and i dont ge why
nevermind, got it working
I need help, Whenever I press the keys for taking damage and healing it gives me an error "Object reference not set to an instance of an object" in Player Behavior. How can I get rid of this error?
It means it can't find the object it is looking for. Most likely you forgot to drag and drop something into a field in the Unity Inspector.
I found the problem, thank you for the help!
@@liam_en3726 Hello, I'm having the same issue, what were you missing?
@@Julesv13 I forgot to make an empty object with the game manager script
i got the nullrefrenceExpetion error how do i fix
thank you so much , can you do an enemy Ai system
to anyone who gets this error:
You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed. MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all UnityEngine.MonoBehaviour:.ctor ()
You are not supposed to generate UnitHealts from Monobehaviour. The problem will be solved when you remove the Monobehaviour part in the script🥲
I didn’t do that in the video? 🙂 I just double checked to make sure that I removed the monobehavior from those scripts.
Edit: Ah just realised this probably wasn’t a correction to the video hehe. 🙂
@@Dani_Krossing Yes you did but it's overlooked, I spent 2 hours trying to figure it out🤦♀😅
How do you do that? If you just delete the :Monobehaviour from the GameManager script, i get other errors like The name 'Destroy' does not exist in the current context [Assembly-CSharp] and highlights the Destroy function from the if statement.
@@rly7123 you will only delete from unithealth script
@@sanemtas4999 Ohh, thanks, now it works
so i finished it, i added it and taking damage works but when i press shift it sets the health to 0. I know i did something wrong 😂
I must have done something wrong, cause I only get an error when I try to run this code: "Object reference not set to an instance of an object". I'm completely new to unity so I got no idea what this means haha, could someone help me out?
It means that your code can't find a object that you are trying to reference. 🙂 So either you forgot to drag a object into your script in the Unity Inspector, or you forgot to add a component to your game object.
These are the most common reasons for this error, and all of them are solved inside Unity, and not in your code.
If you have double checked the above, then next is to check your code for spelling mistakes and typos. 🙂
@@Dani_Krossing Ooooooh I see yeah that makes sense, however I just can't seem to figure out which object I don't have in the Inspector. Playerbehaviour was the only thing you were supposed to drag in, no?
Btw, thanks for such a fast response!
What line does it say the error is on? And can you paste the script the error is in? 🙂
Make sure you check that it is the correct script you paste, that the message says the error is in.
@@Dani_Krossing Sure thing, here it is:
public class PlayerBehaviour : MonoBehaviour
{
void Start()
{
}
void Update()
{
if (Input.GetKeyDown(KeyCode.L))
{
PlayerTakeDmg(20);
Debug.Log(GameManager.gameManager._playerHealth.Health);
}
if (Input.GetKeyDown(KeyCode.K))
{
PlayerHeal(10);
Debug.Log(GameManager.gameManager._playerHealth.Health);
}
}
private void PlayerTakeDmg(int dmg)
{
GameManager.gameManager._playerHealth.DmgUnit(dmg);
}
private void PlayerHeal(int healing)
{
GameManager.gameManager._playerHealth.HealUnit(healing);
}
}
@@astrodoofus7074 Still doesn't work, I seriously don't understand anymore haha
its a shame you didnt show how to use it on an object other than player
Just instantiate the health class inside the script of that object 🙂 Like I did in the GameManager. That’s it.
Awesome tutorial
But I don't now how can I destroy the gameobject when _currentHealth
If (_currentHealth
@@Dani_Krossing Thank you for the quick reply🤩, but in which script do I have to write it? In PlayerBehaviour or UnitHealth?
I am so confused🙈
It's a bit late for this reply, but for anybody else who struggled with this, I handled it like so.
In the script handling your player object:
if (GameManager. gameManager. playerHP. Health
Save these scripts as a template for all your future games!!!
came for a health system and left with a new mental tool and an entire game management system that can restart a level, end a game etc ty
It's way more complicated than any tutorial I've seen. For instance, I'm trying to have the player take damage whevener it collides with an enemy by doing so:
void Update()
{
if(OnCollisionEnter(Collision.gameObject.tag == "Enemy"))
{
PlayerTakeDmg(1);
Debug.Log(GameManager.gameManager._playerHealth.Health);
}
}
But it returns nothing. Is there a simple way to do that?
I noticed that you placed you OnCollisionEnter() inside the Update(), inside an if() statement. Both functions need to be in the scope of the class for it to work, as well as not inside an if() statement. 🙂
Also, yes by making a separate UnitHealth script we make the system slightly more “complex”. But by doing it like this, it becomes much more modular, and reusable in the future. In reality it isn’t really “that complex”, and you’ll notice as you start making games that it is fairly common to separate scripts to make them reusable. 🙂 I’d instead argue that “other tutorials are oversimplifying it”, which makes for bad habits…
I'm struggling with the tutorial; if you could help, it would be very appreciated.
So I have two problems:
You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed. MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all UnityEngine.MonoBehaviour:.ctor ()
^^^
This warning appears without pressing play on the game.
0
UnityEngine.Debug:Log (object)
^^^
Whenever I damage the player or heal, the value is always 0.
This is my code.
*GameManager.cs*__________________________________________________________________________________________________________
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour
{
public static GameManager gameManager { get; private set; }
public UnitHealth _playerHealth = new UnitHealth(100, 100);
void Awake()
{
if (gameManager != null && gameManager != this)
{
Destroy(this);
}
else
{
gameManager = this;
}
}
}
*UnitHealth.cs*_______________________________________________________________________________________________________________
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UnitHealth : MonoBehaviour
{
// Fields
int _currentHealth;
int _currentMaxHealth;
// Properties
public int Health
{
get
{
return _currentHealth;
}
set
{
_currentHealth = value;
}
}
public int MaxHealth
{
get
{
return _currentMaxHealth;
}
set
{
_currentMaxHealth = value;
}
}
// Constructor
public UnitHealth(int health, int maxHealth)
{
_currentHealth = health;
_currentMaxHealth = maxHealth;
}
// Methods
public void DmgUnit(int dmgAmount)
{
if (_currentHealth > 0)
{
_currentHealth -= dmgAmount;
}
}
public void HealUnit(int healAmount)
{
if (_currentHealth < _currentMaxHealth)
{
_currentHealth += healAmount;
}
if (_currentHealth > _currentMaxHealth)
{
_currentHealth = _currentMaxHealth;
}
}
}
*PlayerBehaviour*_________________________________________________________________________________________________
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerBehaviour : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
PlayerTakeDmg(20);
Debug.Log(GameManager.gameManager._playerHealth.Health);
}
if (Input.GetKeyDown(KeyCode.LeftShift))
{
PlayerHeal(10);
Debug.Log(GameManager.gameManager._playerHealth.Health);
}
}
private void PlayerTakeDmg(int dmg)
{
GameManager.gameManager._playerHealth.DmgUnit(dmg);
}
private void PlayerHeal(int healing)
{
GameManager.gameManager._playerHealth.HealUnit(healing);
}
}
I am having the same error, have you found a solution?
@@mysh229 You are not supposed to generate UnitHealts from Monobehaviour. The problem will be solved when you remove the Monobehaviour part in the script