Player Health System #1: Taking Damage (Unity Tutorial)

Ойындар

Beginner-friendly, Unity 2D tutorial showing how to set up a basic health system for your player. This video shows how to link your player's health to enemies, so they can deal damage.
📖 CHAPTERS 📖
0:00 - Demo and Project Setup
0:54 - Writing the Player Health Script
2:24 - Writing the Enemy Damage Script
6:04 - Setting up Enemy Damage in Unity
6:37 - Testing the Setup and Outro
💡 IF ENEMY IS MULT-HITTING THE PLAYER 💡
A common problem for some users is that the enemy multi-hits the player, sometimes even destroying him/her right away. Most often, this is because the enemy detects multiple collisions. As set up, the enemy will deal damage for EVERY collider on the player (including child objects of the player). If you want to make sure that only one collision occurs, edit your script to read:
if(collision.collider.tag == "Player").
Adding the "collider" key word, will cause the damage to only be dealt once per attack, instead of once per collider encountered.
🛑 MUSIC 🛑
🔊Running Out - Patrick Patrikios
Support by RFM - NCM: bit.ly/2xGHypM

Пікірлер: 215

  • @MrMattyMoses
    @MrMattyMoses Жыл бұрын

    This video is perfect for beginners! Straight to the point, and simple to understand thanks to your explanations.

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    Thanks! That’s definitely what I was aiming for, so it’s good to know I hit the mark.

  • @ChrismisHere
    @ChrismisHere Жыл бұрын

    Thank you so much :D (I was sor urprised by how difficult it was for me to find a tutorial on this) To the other readers: The tutorial was easy to follow, good for combining with other scripts and works as it should :)

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    Awww, thanks! Always so pleased to hear that people find these videos useful.

  • @nick_shaba
    @nick_shaba Жыл бұрын

    Дякую! Переглянув багато роликів на цю тему, але тільки ти розповів чисто та зрозуміло

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    I'm so glad it was helpful! Thanks for letting me know :)

  • @MCcrafaak
    @MCcrafaak2 жыл бұрын

    Excellent video with a great and clear explanation, thank you.

  • @NightRunStudio

    @NightRunStudio

    2 жыл бұрын

    Thanks so much for the positive feedback!

  • @clouss
    @clouss Жыл бұрын

    Your videos are clean and understandable. Keep it up.

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    Thanks! I appreciate that feedback--it's good to know what is resonating with viewers.

  • @torontogamestudio2991
    @torontogamestudio2991 Жыл бұрын

    Great Video been trying to figure this out for so long, thanks

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    Thanks for sharing! I'm so glad to hear it helped.

  • @larajanesagun
    @larajanesagun Жыл бұрын

    I just started with unity and have been looking for a video to teach me how to access variable from other scripts because i couldnt make my player health bar to decrease when colliding with the object that's supposed to lessen his health. this is so very helpful. tyvm.

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    Thanks for sharing! I’m so glad you found it helpful. Good luck with your Unity journey!

  • @mastermind1089
    @mastermind1089 Жыл бұрын

    great tutorial! thanks for teaching me how to do this!

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    Glad to hear it helped! Thanks for sharing.

  • @Trickl_
    @Trickl_ Жыл бұрын

    keep up the vids brother, you're a huge help

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    Will do! So glad to hear they are helpful!

  • @TheFinancePod
    @TheFinancePod11 ай бұрын

    Great Video, very clear

  • @NightRunStudio

    @NightRunStudio

    11 ай бұрын

    Thanks for the feedback! That's always good to hear.

  • @SootiestJarl519
    @SootiestJarl519 Жыл бұрын

    This helped me a lot. Thanks!

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    So glad to hear! Thanks for sharing.

  • @darkrager872
    @darkrager872 Жыл бұрын

    These tutorials have an excellent structure and simplicity to them, well worth watching compared to the other tutorials around that are nearer an hour for the same outcome. In saying that however, this does not seem to work for me, I would guess this is due more to spaghetti code of my own creation, but I can see for many more people it does work and is therefore worth it.

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    Thanks for the feedback! Any idea which part isn't working for you? If you can find the part that's breaking down, I might be able to point you in the right direction.

  • @darkrager872

    @darkrager872

    Жыл бұрын

    @@NightRunStudio It seems the player just isn't taking damage, their hitbox registers the collision, and there's no errors inside of unity or the program, the only thing I can see that may indicate an issue is "TakeDamage" doesn't seem to highlight or reference itself inside of the damage script. Everything else is 1:1.

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    If you place a debug.log in takedamage does it print?

  • @darkrager872

    @darkrager872

    Жыл бұрын

    @@NightRunStudio It didn't, but I have figured out the issue! I was using my collider for a patrol function, to turn away from the edge of something and walk back, I clicked off "is trigger" and now the damage function works! The only issue now is my enemy walks into thin air, but hopefully that won't take long to fix.

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    Awesome! So glad you figured it out. Good luck with your project!

  • @Gabriel-rb8tw
    @Gabriel-rb8tw9 ай бұрын

    Life saver, thank you so much

  • @NightRunStudio

    @NightRunStudio

    9 ай бұрын

    Haha... glad to hear it was helpful.

  • @Gabriel-rb8tw

    @Gabriel-rb8tw

    9 ай бұрын

    @@NightRunStudio hahhaha I was following another tutorial and my player was not taking damage nor triggering the hurt animation, I tried to change the code, change the logic, anything. In the end, the player object was not tagged as player… rookie mistake.

  • @NightRunStudio

    @NightRunStudio

    9 ай бұрын

    @@Gabriel-rb8tw We've all done it! Glad you figured it out, at least. :)

  • @ayowolf090
    @ayowolf090 Жыл бұрын

    Thank you! clear and great video

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    You're welcome! I love hearing when people find the videos helpful!

  • @ayowolf090

    @ayowolf090

    Жыл бұрын

    @@NightRunStudio hey, i have a problem. when i turn 'is Trigger' to 'on' the player can go through the floor because it also has a collider on and it can go through the enemy and when i turn if off the player doesnt take damage. How do i stop this?

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    You’ve got a couple of options. You could add another collider (not trigger) which would be your floor detection. You could also switch your script to use onCollisionEnter2D instead of on trigger. Hope that helps!

  • @patricklouieguallar8472
    @patricklouieguallar8472 Жыл бұрын

    Thanks for the huge help!!!!

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    Happy to help! Thanks for sharing.

  • @cheery-hex
    @cheery-hex Жыл бұрын

    thank you so much! great teacher, easy to understand :)

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    Awww… thanks! So glad to hear it was helpful.

  • @garudakin_nz5110
    @garudakin_nz5110 Жыл бұрын

    like and subbed my guy thanks you for the information :D

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    Appreciate it! Thanks for the sub!

  • @niveditaph8778
    @niveditaph8778 Жыл бұрын

    Bro teaches sooo much good n I can Understand everything in the script bro is Second Brackeys :)

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    Haha... wow, that's high praise. So glad to hear this was helpful for you!

  • @niveditaph8778

    @niveditaph8778

    Жыл бұрын

    @@NightRunStudio yes it was

  • @McDonaldsSprite247
    @McDonaldsSprite2476 ай бұрын

    thank you

  • @NightRunStudio

    @NightRunStudio

    6 ай бұрын

    No problem! Glad to hear it was helpful.

  • @nyafnix7060
    @nyafnix7060 Жыл бұрын

    i think its good !!

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    Thanks!

  • @muhammadalimadriansyah5247
    @muhammadalimadriansyah52472 жыл бұрын

    love your tutorial, you help my project a lot

  • @NightRunStudio

    @NightRunStudio

    2 жыл бұрын

    Thanks for sharing! I love hearing that the vids are helping people.

  • @zatzu
    @zatzu Жыл бұрын

    Thank you

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    You're welcome! Glad to hear this was helpful.

  • @laurengoodwin7652
    @laurengoodwin7652 Жыл бұрын

    How would i code it so the health decays over time (every 30 seconds for example) and then collecting health packages increases health (by 3 for example) ?

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    You could definitely adapt this system to include something like you describe. You would just have to create a script that constantly counts down (something like timer -= Time.deltaTime in your Update() method). Then, add an if statement: if(timer

  • @tonycezar1645
    @tonycezar1645 Жыл бұрын

    Great video brother! One question, I have multiple 'friendly' units, how can I reference their health? makes sense when it's just the player, but how can I target a whole group? best regards

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    Unless I’m misunderstanding, the same script should work for all friendly units. As long as they are all tagged as Player, the enemies should only deal damage to the specific player that they collide with. So long as each player has its own copy of the script, then they should each keep track of their own health. For larger games you might eventually want one script to manage all health, but this method should work for most projects.

  • @CoreyBarlow
    @CoreyBarlow Жыл бұрын

    Hey im trying to do this in 3D and all is working okay but for some reason the collisions seem a little off, if i stand still the "enemy" walks over to me and will collide with me but i wont always lose health, i have to walk into the enemy for my health to go down. i have tried messing with the capsule colliders for the player and enemy but nothing seems to be fixing it. would there be a way to code in to take damage if the enemy is within a range of the player's collider and if so how would i code this? (im super new to coding)

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    Collisions are a bit of a fine science. Getting them just right is tricky. You can definitely code to detect nearness to the player, but it’s not the most efficient way to do it in this case. If you want a larger range than you collider currently provides, one option is to add another collider, make it a trigger (so it doesn’t bump into things), and then have your damage detect OnTriggerEnter instead of Collision. Then you can make the damage range as large as you want. Also, remember that this will only trigger on entering the collider. So if the enemy stays in the collider, it will not fire multiple times. To fix this, you would add a knock back effect, that moved the player out of the collider, or use OnCollisionStay with a timer to trigger more damage if the enemy stays inside your collider. I hope that helps!

  • @CoreyBarlow

    @CoreyBarlow

    Жыл бұрын

    @@NightRunStudio u the best

  • @gamdevgamdevpropro2781

    @gamdevgamdevpropro2781

    Жыл бұрын

    i think you have to check the stoping distance in navmesh agent. if sat it lets say 1 than the enemy stops before he colides with you so thats way you have to come closer to enemy . FIX is to change the stopping distance to something closer to 0. i think that would help

  • @nea2933
    @nea2933 Жыл бұрын

    Thank you, this worked really well! I was wondering how I could I gain health from colliding with other objects? For example, when the player collides with an enemy, he loses one heart but if he collides with some other object he would gain one heart instead. So would it be possible to use the same script but instead of taking damage the player would gain hearts? Thanks if you can help!

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    Glad to hear the video was helpful! As for healing items, you are definitely on the right track. It's pretty much damage in reverse :) Good luck with your project!

  • @user-tz8gj8py9j
    @user-tz8gj8py9j6 ай бұрын

    This works well with my enemies aldready in the scene, however enemies appear from spawners are not able to deal damage to me. Any ideas?

  • @NightRunStudio

    @NightRunStudio

    6 ай бұрын

    The problem is probably connected to the prefab that you are spawning in. When the enemy spawns in, he doesn't have the reference to the player (and you can't drag in the reference, because the enemy isn't in the game yet, so Unity wont let you). In order to get a game object script to "talk" to a prefab, you need to have it search for that object. Most often, I do this by placing the following code in the Start() function: playerHealth = GameObject.Find("Player").GetComponent(). Now, the prefab will look for an object called "Player" (or whatever the name of you object is). Once it finds that object, it will search the object to find the Component you need. Note: if your playerHealth script is on a child object, then change GetComponent to GetComponentInChildren. I hope that helps!

  • @MitchIcarus
    @MitchIcarus Жыл бұрын

    I'm almost done but when I get to the step around 6:30 I can't drag my player in, just get the white circle with red edge and diagonal line. Could it be because the enemy is a prefab which I'm spawning in? Or because my player is a prefab I dragged into the hierarchy? What's interesting is that the player within the game doesn't take damage, but the player in my prefab folder does. Edit: I remade my player prefab as a new game object but I still can't drag it into the enemy's damage slot

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    The problem definitely seems to be connected to the prefab--you are correct! Your prefab is just a model of the player, so when your player spawns into the game, it is NOT the prefab, but a copy. This makes things difficult, because you can't use the drag method that I suggest in the video. That said, this is a great chance to learn how to code objects to find their references (which you have to do A LOT as you get into more complex code). In order to get a game object script to "talk" to a prefab, you need to have it search for that object. Most often, I do this by placing the following code in the Start() function: playerHealth = GameObject.Find("Player").GetComponent(). Now, the prefab will look for an object called "Player" (or whatever the name of you object is). Once it finds that object, it will search the object to find the Component you need. Note: if your playerHealth script is on a child object, then change GetComponent to GetComponentInChildren. I hope that helps!

  • @japanlearneracc1126
    @japanlearneracc11268 ай бұрын

    hello, I have a question. I have put the damage script on the player so when the player touches enemy it damages him but it only works on the first collision. when they collide more than once it doesnt damage player anymore. I also tried using OnCollisionStay2D but it has the same effect.

  • @NightRunStudio

    @NightRunStudio

    8 ай бұрын

    So if you leave and come back you still don’t have any effect? That is strange, indeed. If you want to share your code I could take a look.

  • @Sienna998
    @Sienna998Ай бұрын

    Would there be a way to make the enemy script work on an enemy that shoots? I have 2 types one that follows and does damage when it touches and one that follows and shoots when it's a certain distance from the player. I did try attaching the same script to the bullet but of course I can't connect the player health to it. Lol

  • @NightRunStudio

    @NightRunStudio

    Ай бұрын

    You are on the right track! That should work, you just have to code the bullet to find the player. My more recent playerHealth video shows this (in case you want to see it explained), but here's what you need to make it work: In your OnCollisionEnter() method for the damage script, have it check any object it hits to see if it is the player, and if it is, have it fill the playerHealth variable with the object it just hit (ie., the player). private void OnCollisionEnter2D(Collision2D collision) { // Attempt to get the PlayerHealth component from the collided object if(collision.gameObject.TryGetComponent(out PlayerHealth playerHealth)) { // If the PlayerHealth component is found, assign it to the class variable this.playerHealth = playerHealth; } } I hope that helps!

  • @requiem139
    @requiem1392 жыл бұрын

    Hi, i have a question. So the tutorial is great, but i don't know how to do it with a prefab. I can't drag the player to the prefab. Do you have an idea?

  • @NightRunStudio

    @NightRunStudio

    2 жыл бұрын

    If your player is a prefab, you will have to do it through code. Adding GameObject.Find(“Player”); Into your Start() function should do the trick (assuming your player is called Player). If that doesn’t work (or I misunderstood your problem) let me know. You can always PM me on Twitter if that’s easier.

  • @requiem139

    @requiem139

    2 жыл бұрын

    @@NightRunStudio Thank you, i think this should work. I'm gonna try it out

  • @DillonChal

    @DillonChal

    Жыл бұрын

    @@NightRunStudio I am having the same issue. My player is not a prefab but the enemies with the damage script are. I have tried adding what you mentioned above into the start() function, however, I still seem to be having an issue.

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    @@DillonChal Hmmn... can't think of why this wouldn't work for you then. Did you remember to tag your player as "Player"? Feel free to PM me on twitter and send a screenshot of your code, and I can take a closer look if you like.

  • @TurningTrix42

    @TurningTrix42

    Жыл бұрын

    @@NightRunStudio I have a similar issue with my enemies being prefabs. The code that won't work, isn't damage being given to the player, but that I have 3 hearts in the top left that represent the players health (Player loses a heart every time it takes damage. The Player is damage when the enemy touches the Player). However since the enemies are prefabs, it won't allow me to put in the "Health Controller" object (which shows the images for the hearts and the hearts get removed each time the Player taking damage). The "Health Controller" is in my Hierarchy as a child under the Player (I just found out today that prefabs cannot reference Scene Objects). If I drop an enemy object in to the Scene, it works, but the idea is that the enemy prefabs continuously spawn on the edges of the map and move towards the player rather than starting out in the scene. Not sure how I can get the prefabs to perform the "Health Controller" to remove a heart when they deal damage to the player. (Sorry, very new to coding, so hopefully this makes sense)

  • @yoimhana76
    @yoimhana7610 ай бұрын

    hi there! thank you so much for the tutorial, it's helping me out a lot for a project i have due. i've quite literally never worked with code before and it's been daunting. i do however have a question alright - i've looked at every single comment on this page and have still not been able to find out what my problem is despite so many other commenters having the exact same problem I'm having: my prefab enemy (a meteor with the enemy script) is unable to accept the fill in field from my player (a spaceship, tagged UFO) and thus whenever i hit play, there is no collision and there is no damage taken from my player ship. i've inserted the "find component for player health" in the start function of the enemy script attached to my enemy prefab as ive seen the solution be for a few other people. my prints arent registering. this is the error I get when playing: "NullReferenceException: Object reference not set to an instance of an object EnemyDamage.Start () (at Assets/EnemyDamage.cs:15)" which I don't know what this means - i know that enemy damage is not set to an instance of an object because i can't fill the inspector with the player script. i'm not sure if i explained that well enough - i can def rephrase if necessary and i can share my code if you'd like to see it as well. again, thank you so much for your tutorials, really appreciate them and how it's expanding my understanding.

  • @NightRunStudio

    @NightRunStudio

    10 ай бұрын

    It definitely sounds like you’ve identified the problem. The null reference sounds like it is on line 15 of your code, and it sounds like it’s the reference to your player health that is coming up null. The reason you can’t drag the PlayerHealth into that slot is because both objects have to be in the scene before they can start talking to each other. The get component call should work, so I suspect it may be something to do with the way you are calling it. Feel free to share that line of code, or to pop into my discord server for a better discussion forum (link is in the profile).

  • @juliapaulewicz1471
    @juliapaulewicz14716 ай бұрын

    the console says "The type or namespace name 'PlayerHealth' could not be found (are you missing a using directive or an assembly reference?)". :(( how do i fix this?

  • @NightRunStudio

    @NightRunStudio

    6 ай бұрын

    That usually means a spelling or capitalization error. The name in your script needs to exactly match the name of the script you are talking to. Sometimes this happens after renaming a script… sometimes when you rename, Unity doesn’t actually change the name in the script itself. Definitely double check that both the script in Unity and the script itself have the same class name. I hope that helps!

  • @KTIKNA
    @KTIKNA4 ай бұрын

    can you give the player and enemy script as a whole?

  • @shwooom8862
    @shwooom88626 ай бұрын

    Loved this video! but after I followed everything the player still won't take damage!! I had this problem trying to do the same thing yesterday using another script... any idea why it wont work? its all set up the same as yours, he just wont take damage off the enemy even though damage is set to 2 ;(

  • @NightRunStudio

    @NightRunStudio

    6 ай бұрын

    If your script is identical then it’s usually an issue in Unity. Did you remember to fill the appropriate boxes in the inspector? (So they can talk to the player’s health script). Are you getting any error statements in the console?

  • @thesossypus7347
    @thesossypus7347 Жыл бұрын

    I got an error saying collision does not exist in the current context when i did the first part of the enemy damage scrip and i dont know how to fix it

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    That error is usually a spelling or capitalization error. Maybe double check your collision and tag spellings. If you can't find the problem, feel free to copy in your code and I can take a look.

  • @thesossypus7347

    @thesossypus7347

    Жыл бұрын

    @@NightRunStudio yup, i think that was it thanks

  • @glyukzt1
    @glyukzt1 Жыл бұрын

    I fixed the issue with player not taking damage by creating a new tag and placing it into the script

  • @tonytristianto1395

    @tonytristianto1395

    Жыл бұрын

    can u share the project ?

  • @OurCumrade
    @OurCumrade Жыл бұрын

    Hello great tutorial but I had a doubt. I want the damage to be done by a "bullet" the bullet is tho a asset so i am unable to drop player on the script unless i make it a game object pls help Even if i add the bullet to the scence it when clones itself it's script always has to drag and drop the player between game. and it still is taking no damamge

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    Yeah, prefabs are tricky! You will have to code the bullet to find the player once it spawns into the scene. To do this, you will have to put something like this in the Start() method: PlayerDamage = GameObject.Find(“Player”).GetComponent(); You will, of course, still need your reference to the player’s damage script at the top of your script (something like public PlayerDamage playerDamage). This assumes your player is named Player and your damage script is called DamagePlayer.

  • @OurCumrade

    @OurCumrade

    Жыл бұрын

    @@NightRunStudio I can make it reach the player but the it does not do any damage because the bullet gets clone each time. Still thanks for responding it's so awesome you reply to comments even when the video is months old.

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    @@OurCumrade Just to clarify: By "Find" the player, I mean that it needs to be able to talk to the player's script. Because they are prefabs, each bullet will need to manually find the player's health script once it spawns into the game (that way it can tell you to take damage when it hits you). If that doesn't help, feel free to paste a copy of your script and I can take a look.

  • @duckinhoodie3212
    @duckinhoodie3212 Жыл бұрын

    hey, nice video but it seems like it doesnt work for me. The player isn't taking damage from the enemy when a collision is happening. I'm using polygon colliders 2D. Can anyone help me?

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    I'll need a little more information, but I'd be happy to help you troubleshoot. My first thought is to put a debug.log at the top of your OnCollision method, just to make sure that the collision is, in fact, registering. Something like: Debug.Log("Just collided with " + collision.gameObject.name): That should print the name of the object you collide with in your console. If it doesn't, you know it's probably a problem in your inspector. If it DOES print, then we know the collisions, are working and it's a code issue.

  • @brusty1260
    @brusty12602 жыл бұрын

    hey so i was wondering what i would use instead calling oncollisionenter2D if im using a 3d player/enemy

  • @NightRunStudio

    @NightRunStudio

    2 жыл бұрын

    If you are working with 3D colliders, you can just use OnCollisionEnter (instead of OnCollisionEnter2D). The key is to make sure that your function call matches the type of collider you use (2D collider gets OnCollision2D, and 3D gets regular OnCollision call).

  • @brusty1260

    @brusty1260

    2 жыл бұрын

    @@NightRunStudio have you got a discord server i could join or a discord i could message with some pastebin links and screenshots?

  • @NightRunStudio

    @NightRunStudio

    2 жыл бұрын

    I don’t yet. You could fire me some screen shots in Twitter, though. I’d be happy to take a look.

  • @EnnoTTT
    @EnnoTTT Жыл бұрын

    Good video, this helped me a lot! but instead of destroying the player, how can i respawn him instead? I dont want the game to end, i want the player to respawn from the last checkpoint

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    I'm hoping to do a video on respawning and checkpoints soon, but in the meantime, here's one way you might go about this: 1) Declare this variable at the top of the health script: public Vector2 respawnPoint; (You can fill in these coordinates inside of Unity) 2) Now, when you die, instead of destroying the player, type: transform.position = respawnPoint; That should do it! Let me know if you have any troubles.

  • @EnnoTTT

    @EnnoTTT

    Жыл бұрын

    @@NightRunStudio thank you! I will try that

  • @EnnoTTT

    @EnnoTTT

    Жыл бұрын

    @@NightRunStudio the player does now respawn instead of destroy, but the player spawns at 0 x and -3.4 y. i typed in 80 on the x and -3.4 on the y, so y works but not x for some reason. Do you know why? Also, if i want the player do spawn at different positions as the level goes on (checkpoints), how would i do that

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    @@EnnoTTT Yikes! That's a weird one. If your sprite is on a child object (like the sprite, instead of the parent player object) then you are probably being teleported relative to the player's position. For example, if you want to teleport to x = 4, you will end up 4 units to right of the parent object. If you want the child to set the position of the parent object, you'll have to add that to the code. One way to do this is: 1) Create a reference to the parent: public GameObject parent; (and then drag you parent into the new box you created in Unity). 2) Change your code to: parent.transform.position = (whatever position you want to go to) This should move the parent, instead of the child object. I hope that makes sense and helps!

  • @EnnoTTT

    @EnnoTTT

    Жыл бұрын

    @@NightRunStudio thank you very much! It works now (: but now that the player respawns the players health doesnt reset. The player respawns after being hit once after the first respawn, the players health then goes to -1 and then -2.. How could i reset the players health (wich is 3 for me) every time the player 'dies' (respawns)?

  • @mikumikumilk9165
    @mikumikumilk9165 Жыл бұрын

    My enemy is a prefab. Can't get player slided to the Player slot. Same issue with other guy as follows = Itadiuch 3 months ago Hi, i have a question. So the tutorial is great, but i don't know how to do it with a prefab. I can't drag the player to the prefab. Do you have an idea?

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    Yeah, it’s trickier with prefabs. The good news is that this is really useful code to learn for many other situations. To get a prefab to “talk” to a script of another object, you have to type the following into your Start() function: GameObject.Find(“PlayerName”).GetComponent(); Now, when the enemy comes into the game, he will immediately find your player, then find the health component in your player. Hope that helps!

  • @Cjoudan

    @Cjoudan

    Жыл бұрын

    @@NightRunStudio I tried this and it still does not work. not sure what the deal is, my debug log isn't showing the damage coming through?

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    @@Cjoudan Sounds like the problem is probably that your damage script isn't accessing your playerHealth script. Does the box for your playerHealth script show up in the inspector in unity? If so, Once you start play test, does the box fill up or remain empty? If it is empty, that's definitely a problem. Most likely it is something to do with your GetComponent call. It is important here that you correctly type the name of your player game object (the one that the script is on... it won't work if the script is on a child), and the name of the script. Note, if your player health script is on a child of the player, you can chance to component call from GetComponent to GetComponentInChildren. Hope that helps!

  • @Cjoudan

    @Cjoudan

    Жыл бұрын

    @@NightRunStudio Thank you, i'll give it a go!

  • @oDWreckz

    @oDWreckz

    Жыл бұрын

    @@NightRunStudio Sorry for asking but what script would you add this into?

  • @tonoobforyouiv3783
    @tonoobforyouiv37838 ай бұрын

    Just two questions. 1. how can I create a kind of delay before the player takes damage so that the player has to stay in contact with the enemy for a few moments before taking damage? 2. how can I make it so the player only has to get within a certain radius of the enemy before taking damage?

  • @NightRunStudio

    @NightRunStudio

    8 ай бұрын

    I'll start with the radius as that is most simple. I would recommend creating a large collider around your enemy (I like circle collliders) that represents their damage range. Then, use OnTriggerEnter2D as the method in your code (you can use this instead of OnCollision, or in addition to it). Place your damage logic in the OnTrigger method. Now, whenever the player enters that trigger, it will call the damage logic.

  • @NightRunStudio

    @NightRunStudio

    8 ай бұрын

    The delay is a little more complex, so I wont be able to explain the details here, but I'll point you in the right direction. For this one, you will probably want to use a coroutine. When the player enters the trigger, call StartCoroutine. Then, you create a coroutine (like a normal method, but these allow you to pause time). You would put all of your damage logic in the coroutine, but first add yield return new WaitForSeconds(2); this would pause the script for 2 seconds before moving on to the damage part. I hope that helps you get started!

  • @tonoobforyouiv3783

    @tonoobforyouiv3783

    8 ай бұрын

    @@NightRunStudio thanks I'll see if I can get it to work

  • @harethkhoja3738
    @harethkhoja37389 ай бұрын

    est didn't work although I didn't get an error message. If I touch the opponent I die

  • @NightRunStudio

    @NightRunStudio

    9 ай бұрын

    It's hard to know what's wrong without more information. If you are getting destroyed, then it sounds like it might be an issue with you "if" that checks to see if you've run out of health. Additionally, it could be that your enemy is dealing too much damage and one-shotting you, or that the player doesn't have its health set to full. Those are the first places I would look for a fix.

  • @loofy8135
    @loofy81359 ай бұрын

    Sorry another question for you, your last fix was perfect! But again I am a little confused, when I walk on the ground or any object I lose health, no matter what I touch, any clue why?

  • @NightRunStudio

    @NightRunStudio

    9 ай бұрын

    Are you using a tag so that your player knows when he collides with an enemy vs. colliding with the ground?

  • @loofy8135

    @loofy8135

    9 ай бұрын

    I had colliding scripts so I apologize, that's my bad! Do you have any good video's about when a player takes damage they get some kick back from the enemy? My player keeps taking 2-3 hearts because he just rubs against the enemy but I don't know how to make his get pushed back!@@NightRunStudio

  • @NightRunStudio

    @NightRunStudio

    9 ай бұрын

    I have a few versions of knockback. There is one in my 2D enemies, one in my tower defense series, and one in the melee attack. It just depends on what you want to achieve. As for taking extra damage, when you call the collision.gameObject line under OnCollision, try using collision.collider.gameObject instead. This should make it only fire once (otherwise it fires for all the colliders on the object which can cause damage to happen multiple times.

  • @loofy8135

    @loofy8135

    9 ай бұрын

    Sweet! You're the best, thank you!!!@@NightRunStudio

  • @jambon9613
    @jambon9613 Жыл бұрын

    so my player only takes 2 damage and then cant be damaged again and for some reason they arent colliding and moving but are still taking damage. i hope that makes sense

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    I'm not totally clear... does the player only take damage once, or are they "still taking damage" even when standing still? Both problem can happen, but they are usually opposites. The way this script is set up, you will only take damage 1 time, and will have to leave the enemy's collider before taking damage again (I recommend adding knockback so that the enemy pushes you out of it's collider, that way when you re-enter the damage should happen again).

  • @jambon9613

    @jambon9613

    Жыл бұрын

    @Night Run Studio the player takes damage once, then once you leave the collider, he just doesn't take damage anymore

  • @jambon9613

    @jambon9613

    Жыл бұрын

    when i turn off box collider the player takes no damage and when i put them on the player takes 4 damage or multiple hits

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    @@jambon9613 That's some super weird stuff. If you want to pop onto my discord channel and share your code, I can take a look and see if I can help out. discord.gg/cNwEwYHf

  • @jambon9613

    @jambon9613

    Жыл бұрын

    @Night Run Studio yeah I might do that tomorrow thanks

  • @acrow4969
    @acrow49694 ай бұрын

    theres a wierd line thing in you rgame, i think theres a way to fix it with th eliek sprite sheet or textures something with the settings just wanted to let you know cause it fucked me up when i was making my 2d games.

  • @NightRunStudio

    @NightRunStudio

    4 ай бұрын

    Thanks for that! I have since figured out the reason, but it's thoughtful of you to take the time to make the comment. Cheers!

  • @ghostgamer260
    @ghostgamer260 Жыл бұрын

    The player doesn’t seem to take any damage even when hit. Any ideas?

  • @ghostgamer260

    @ghostgamer260

    Жыл бұрын

    The health stays at 10.

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    My first move when something like that happens is to put a Debug.Log statement at the top of the OnCollision function. That way you can check to see if the collision is even being detected. If not, you know it’s a problem with your colliders.

  • @_arcadian._
    @_arcadian._ Жыл бұрын

    For some reason if my function isn't in the update it doesn't work, and putting it in the update kills the player almost immediately because he loses health the second he colides with the enemy collider.

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    Yeah... you definitely don't want to put it there (then it runs like 60 times per second). There must be another reason that it's not being called. Do you want to copy/paste your code here, and I'll take a look?

  • @_arcadian._

    @_arcadian._

    Жыл бұрын

    I am sorry in advance, my code is kind of long. I think the problem might be because my enemy is moving towards the player. float horizontalInput; public float speed = 2f; public float jumpForce = 2f; public int health; public int maxHealth; public Rigidbody2D myRigidBody; public CapsuleCollider2D myCollider; public Animator myAnimator; public BoxCollider2D myBoxCollider; // Start is called before the first frame update void Start() { health = maxHealth; myRigidBody.GetComponent(); myCollider.GetComponent(); myAnimator.GetComponent(); myBoxCollider.GetComponent(); } // Update is called once per frame void Update() { IsGrounded(); horizontalInput = Input.GetAxisRaw("Horizontal"); //Walk if(horizontalInput != 0) { transform.localScale = new Vector3(horizontalInput, transform.localScale.y, transform.localScale.z); myAnimator.SetBool("isWalking", true); } else { myAnimator.SetBool("isWalking", false); } //Jump if(Input.GetKeyDown(KeyCode.Space) && IsGrounded()) { myRigidBody.velocity = new Vector2(myRigidBody.velocity.x, myRigidBody.velocity.y + jumpForce); } } void FixedUpdate() { myRigidBody.velocity = new Vector2(horizontalInput * speed, myRigidBody.velocity.y); } bool IsGrounded() { if (myBoxCollider.IsTouchingLayers(LayerMask.GetMask("Collideable"))) { myAnimator.SetBool("isJumping", false); return true; } else { myAnimator.SetBool("isJumping", true); return false; } } public void TakeDamage( int amount) { if (myCollider.IsTouchingLayers(LayerMask.GetMask("Enemy"))) { health -= amount; if(health

  • @_arcadian._

    @_arcadian._

    Жыл бұрын

    Here is the enemy movement script in case that helps. Thank you super much for looking into this, also. public float speed; public bool chase = false; public Transform startingPoint; private GameObject player; // Start is called before the first frame update void Start() { player = GameObject.FindGameObjectWithTag("Player"); } // Update is called once per frame void Update() { if (player == null) return; if (chase == true) Chase(); else ReturnStartPoint(); Flip(); } private void Chase() { transform.position = Vector2.MoveTowards(transform.position, player.transform.position, speed * Time.deltaTime); } private void Flip() { if (transform.position.x > player.transform.position.x) transform.rotation = Quaternion.Euler(0, 0, 0); else transform.rotation = Quaternion.Euler(0, 180, 0); } private void ReturnStartPoint() { transform.position = Vector2.MoveTowards(transform.position, startingPoint.position, speed * Time.deltaTime); }

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    @@_arcadian._ Just to clarify, Is it the Take Damage function that is not running?

  • @_arcadian._

    @_arcadian._

    Жыл бұрын

    @@NightRunStudio Yes, i checked with the debug

  • @talismanskulls2857
    @talismanskulls2857 Жыл бұрын

    First, thanks for these videos. Unfortunately it didn't work with what I was trying to apply it to even as a test. I have a Game Controller that if the player is hit with a Destroy by Contact (shots, enemies, hazards) the Player health bar would drop with each impact. Right now one collision ends game till Restart. I wanted to try and set it so once Health is empty or 0, there would be taken away 1 life (IE heart Icon) and reset health bar to 100 with each remaining life. Then when all the lives are exhausted (say 3) and the health has reached zero, then the game is over, and you have to restart. SO I need some sort of simple and straightforward way to reference all three scripts properly. The Player Heath, the Destroy by Contact, and the Game Controller. I have tried several Health systems and not a single one works with the other two scripts and certainly does nothing to tick away the heath bar much less any spare lives. Been trying to do this for days spending 12+ hours just to find something that will work properly.

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    Hmmn...I have a couple of thoughts... First: Is your Destroy script auto-destroying, or is it just that your collisions are being mult-triggered, so that you lose multiple health each time you collide? If you have multiple colliders on your player (or on child objects), it's possible all of these are triggering each time you get hit. Second: Sounds like you need to create a "Lives" int in your Game Controller. Then, rather than destroying your player each time he reaches zero, you could have your Destroy script tell the Game Controller to take another life. This would look something like: if(PlayerHealth.health

  • @cxianb
    @cxianb Жыл бұрын

    if you want to put this in 3D the enemy damage should be this using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyDamage : MonoBehaviour { public PlayerHealth playerHealth; public int damage = 10; private void OnCollisionEnter(Collision collision) { if(collision.gameObject.tag == "Player") { playerHealth.TakeDamage(damage); } } }

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    Thanks for sharing this! I'm sure a few people will find it helpful. Cheers!

  • @ojwy122

    @ojwy122

    11 ай бұрын

    thanks bro

  • @nee379
    @nee379 Жыл бұрын

    I cant quite seem to make 3D work

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    If you're working in 3D, you will need to make sure that you are using regular colliders, and that your code is OnCollision as opposed to OnCollision2D. That would be my first guess without more information. Feel free to DM me on Twitter if you want to send some screenshots or anything like that.

  • @nee379

    @nee379

    Жыл бұрын

    @@NightRunStudio Alright thank you!

  • @mhd3117
    @mhd31175 ай бұрын

    hi attach the script pleaseeeeeeeeeee

  • @readypanda5116
    @readypanda5116 Жыл бұрын

    i works perfectly.... only my enemy stops moving after collision with the player good video though

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    That’s a really strange bug! If you want to paste your code, I could take a look.

  • @CarlozYT
    @CarlozYT Жыл бұрын

    6:33 i cant seem to place my player into the box?

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    Two questions: 1) is your PlayerHealth script on the player game object? (That's what the box is looking for). 2) Is your player a prefab (If he is not currently in the scene, we need to add a few lines of code)

  • @CarlozYT

    @CarlozYT

    Жыл бұрын

    ​@@NightRunStudio 1. i coded it under my character controller script 2. its not my player who is a prefab its a bullet i made wich will hit the player

  • @CarlozYT

    @CarlozYT

    Жыл бұрын

    @@NightRunStudio my game is basically this guy running around and guns at each side of the screen trying to shoot him and ive got the hit detection to work but not the health system

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    @@CarlozYT Gotcha. The reason you can't drag the player in is because the bullet is a prefab (which means it doesn't exist in the scene until you instantiate it). The way around this, is the have the bullet find the PlayerHealth script once it is instantiated. In the bullet script, go to the Start() function. You will need to type: playerHealth = GameObject.Find("PlayerName").GetComponent(); This will let the bullet fill the box by itself. It will find the player (make sure to type the exact name of your player), and then find the script on your player. I hope that helps!

  • @CarlozYT

    @CarlozYT

    Жыл бұрын

    @@NightRunStudio IT WORKS TYSM

  • @Stripho
    @Stripho5 ай бұрын

    keeps saying there's an error. i can't even find what i did wrong

  • @NightRunStudio

    @NightRunStudio

    5 ай бұрын

    What error is it giving you?

  • @Stripho

    @Stripho

    5 ай бұрын

    i fixed it, motherfluffin spelled "gameobject" wrong 💀@@NightRunStudio

  • @sil3ntn0ob48
    @sil3ntn0ob48 Жыл бұрын

    I am getting this error: Object reference not set to an instance of an object Damagee.OnCollisionEnter2D (UnityEngine.Collision2D collision)

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    Anytime you see that error it is telling you that you forgot to define a variable reference. In this case, I'm willing to bet it's your playerHealth variable. The script knows it hit your player, and now it wants to talk to the playerHealth script, but it doesn't know where to find it. To fix this, just drag your player into the PlayerHealth slot in the enemy's inspector (I do this around 6:22 in the video). Hope that helps!

  • @sil3ntn0ob48

    @sil3ntn0ob48

    Жыл бұрын

    @@NightRunStudio Thanks this helped

  • @samchristian9149
    @samchristian9149 Жыл бұрын

    Hey whenever I have my player run into the enemy the debug I put doesn't print. private void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.tag == "Player") { Debug.Log("hello"); playerHealth.TakeDamage(damage); } } Is what I have, my player is tagged as Player in the inspector so i don't know what im doing wrong

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    The code looks all good. Must be an issue in Unity. Does either your player or the enemy have a rigid body 2d? (One has to or the collisions won’t detect). Also, did you make sure that both have 2D colliders? And that the colliders are not triggers? Just a few things to check to get you started.

  • @samchristian9149

    @samchristian9149

    Жыл бұрын

    @@NightRunStudio both have rigid bodies and both use capsule colliders. I didn’t add any ticks to either of the colliders so it maybe be that.

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    Are both the colliders and the rigid bodies the 2D version?

  • @samchristian9149

    @samchristian9149

    Жыл бұрын

    @@NightRunStudio yep I’m doing a top down style game but I don’t think that should make it different

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    @@samchristian9149 This seems really weird. You did capitalize the P on your player tag, right?

  • @aleksandraaleksandra7934
    @aleksandraaleksandra7934 Жыл бұрын

    Hi folks, I get a message: NullReferenceException: Object reference not set to an instance of an object, but everything works fine, i.e. damage is done by the enemy. I don't know how to fix it?

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    If you click on the error message, it should take you to the line that is causing the problem. A null reference just means that your script is looking for something but can't find it (often this is a reference to another script). Once you know what it's missing, it will be easier to figure out why it can't find that reference.

  • @aleksandraaleksandra7934

    @aleksandraaleksandra7934

    Жыл бұрын

    @@NightRunStudio Your answer helped me🙌 . I analyzed the code and found a bug. I mistakenly referenced GetComponent to the script "PlayerMovement" instead of "PlayerHealth" - it was inadvertently😒. Now the error does not appear anymore, but when the player is destroyed by the enemy, the message appears: "The object of type 'GameObject' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object." This message refers to my Enemy's AI. I'm guessing there's a situation where my player disappears. I don't know how to do it yet, for now I want to study your tutorials in the playlist of the current topic. You are great! Thank you for your materials and help.💗

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    @@aleksandraaleksandra7934 I'm so glad you are finding the videos helpful! Thanks for sharing. The null reference probably has to do with your character being destroyed, but the game is still trying to talk to scripts on your player. As your game develops, we generally move away from destroying the player on death (for this reason), and instead turn off specific elements of the player (like your sprite and movement scripts). For the moment, those errors should cause any serious problems (since your player is dead anyways). I hope that makes sense. Good luck as you continue to learn!

  • @aleksandraaleksandra7934

    @aleksandraaleksandra7934

    Жыл бұрын

    @@NightRunStudio In the further part of building the game, I will try to disable the player's moving option and return to the beginning of the level using the if statement. It will be void PlayerDie() or something like that. This should probably work :) I've done something similar before, I'll try to recreate it.

  • @aleksandraaleksandra7934

    @aleksandraaleksandra7934

    Жыл бұрын

    I fixed this problem. It turned out to be due to a reference to the player object in an old script that was unused and became an artifact. So a protip for everyone who makes a game: organizing your scripts is important! :-). If you get a similar error, it's worth looking at the script that the console message sends you to and see where the script refers to the player object. Either it will be a mess like mine or you may need to add TakeDamage() in this script. I'm not sure about the second solution!

  • @percyrogers7246
    @percyrogers7246 Жыл бұрын

    this is the error i get with enemy damage but renamed as weapon WeaponDamage.cs(25,22): error CS1061: 'Collision' does not contain a definition for 'Gameobject' and no accessible extension method 'Gameobject' accepting a first argument of type 'Collision' could be found (are you missing a using directive or an assembly reference?) using System.Collections; using System.Collections.Generic; using UnityEngine; public class WeaponDamage : MonoBehaviour { public PlayerHealth playerHealth; public int damage = 25; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } private void OnCollisionEnter(Collision collision) { if(collision.Gameobject.tag == "player") { playerHealth.TakeDamage(damage); } }

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    I'm just noticing two possible issues at a quick glance: 1) Are you working in 3D? If so, then it's all good. Otherwise, be sure to change your OnCollisionEnter to the 2D version. 2) Be careful with capitalization! (They will get you every time :) your gameObject reference should have a lowercase "g" and uppercase "o". Hope that helps!

  • @percyrogers7246

    @percyrogers7246

    Жыл бұрын

    @@NightRunStudio it's a 3d project but i changed it but got this error now. error CS1061: 'Collision' does not contain a definition for 'gameoOject' and no accessible extension method 'gameoOject' accepting a first argument of type 'Collision' could be found (are you missing a using directive or an assembly reference?)

  • @NightRunStudio

    @NightRunStudio

    Жыл бұрын

    @@percyrogers7246 it's important to get the spelling exactly right. It looks like your gameObject is still spelled incorrectly. That would definitely give you an error.

  • @percyrogers7246

    @percyrogers7246

    Жыл бұрын

    @@NightRunStudio sorry i didn't see the extra o. i got it now, but rechanged it and it says expected now.

  • @percyrogers7246

    @percyrogers7246

    Жыл бұрын

    @@NightRunStudio i got it thank you so much. it was the playerHealth it couldn't find.

  • @BomberManHipHop
    @BomberManHipHop8 ай бұрын

    Is the enemy script not able to work for enemy prefabs..?🫠

  • @NightRunStudio

    @NightRunStudio

    8 ай бұрын

    It does work; you just have to add a line so the enemy and player can talk to each other. In the start method of the script, you just have to add: playerHealth = GameObject.Find("PlayerGameObjectName").GetComponent(); make sure to use the exact name of the game object that holds the PlayerHealth script. Hope tha thelps!

  • @BomberManHipHop

    @BomberManHipHop

    8 ай бұрын

    @@NightRunStudio thank you so much for the feedback! I just got Settled in from work, boutta give it a try. Thank you again

Келесі