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

Поділитися
Вставка
  • Опубліковано 22 лис 2024

КОМЕНТАРІ • 217

  • @MrMattyMoses
    @MrMattyMoses Рік тому +7

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

    • @NightRunStudio
      @NightRunStudio  Рік тому +3

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

  • @ChrismisHere
    @ChrismisHere Рік тому +6

    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  Рік тому +3

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

  • @larajanesagun
    @larajanesagun Рік тому +1

    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  Рік тому +1

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

  • @darkrager872
    @darkrager872 Рік тому +3

    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  Рік тому +1

      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  Рік тому +1

      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  Рік тому +1

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

  • @nick_shaba
    @nick_shaba 2 роки тому +1

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

    • @NightRunStudio
      @NightRunStudio  2 роки тому

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

  • @clouss
    @clouss Рік тому +3

    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.

  • @Gabriel-rb8tw
    @Gabriel-rb8tw Рік тому +3

    Life saver, thank you so much

    • @NightRunStudio
      @NightRunStudio  Рік тому +1

      Haha... glad to hear it was helpful.

    • @Gabriel-rb8tw
      @Gabriel-rb8tw Рік тому +1

      @@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  Рік тому +1

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

  • @ShenntrenSapam
    @ShenntrenSapam 3 місяці тому +1

    Hi I have a problem where the player just takes the damage once But I want the player to take damage continiously btw the tutorial was pretty great! Thanks

    • @NightRunStudio
      @NightRunStudio  3 місяці тому

      Glad the video was helpful!
      This system is sort of set up where it needs you to add a knockback effect-each time you re-enter you would take damage.
      To create continuous damage, you’d have to set it up a little differently (as this one only works when you enter the collision). You’d want to use OnCollisionStay2D() for continuous damage, and you’d need to introduce a timer (so it deals damage, say, once every .5 seconds). I hope that points you in the right direction!

  • @torontogamestudio2991
    @torontogamestudio2991 2 роки тому +1

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

    • @NightRunStudio
      @NightRunStudio  2 роки тому

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

  • @niveditaph8778
    @niveditaph8778 Рік тому +1

    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

  • @mitchellfrank16
    @mitchellfrank16 Рік тому +1

    Great Video, very clear

    • @NightRunStudio
      @NightRunStudio  Рік тому

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

  • @mastermind1089
    @mastermind1089 2 роки тому +1

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

    • @NightRunStudio
      @NightRunStudio  2 роки тому

      Glad to hear it helped! Thanks for sharing.

  • @xhi4xhi432
    @xhi4xhi432 3 місяці тому +1

    Perfect thank you

  • @ayowolf090
    @ayowolf090 Рік тому +1

    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  Рік тому +1

      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!

  • @SootiestJarl519
    @SootiestJarl519 Рік тому +1

    This helped me a lot. Thanks!

  • @cheery-hex
    @cheery-hex 2 роки тому +1

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

    • @NightRunStudio
      @NightRunStudio  2 роки тому +1

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

  • @Trickl_
    @Trickl_ Рік тому +1

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

  • @tonycezar1645
    @tonycezar1645 Рік тому +1

    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.

  • @cxianb
    @cxianb Рік тому +3

    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 Рік тому +1

      thanks bro

  • @EnnoTTT
    @EnnoTTT 2 роки тому +2

    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  2 роки тому +2

      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 2 роки тому +1

      @@NightRunStudio thank you! I will try that

    • @EnnoTTT
      @EnnoTTT 2 роки тому

      @@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  2 роки тому +1

      @@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 2 роки тому +1

      @@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)?

  • @patricklouieguallar8472
    @patricklouieguallar8472 Рік тому +1

    Thanks for the huge help!!!!

  • @nearlyheree
    @nearlyheree Рік тому +1

    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  Рік тому +1

      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!

  • @glyukzt1
    @glyukzt1 Рік тому

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

    • @HrxTon
      @HrxTon Рік тому

      can u share the project ?

  • @garudakin_nz5110
    @garudakin_nz5110 Рік тому +1

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

  • @zatzu
    @zatzu Рік тому +1

    Thank you

    • @NightRunStudio
      @NightRunStudio  Рік тому

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

  • @requiem139
    @requiem139 2 роки тому +4

    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 роки тому +1

      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 роки тому +1

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

    • @DillonChal
      @DillonChal 2 роки тому +2

      @@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  2 роки тому

      @@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)

  • @muhammadalimadriansyah5247
    @muhammadalimadriansyah5247 2 роки тому

    love your tutorial, you help my project a lot

    • @NightRunStudio
      @NightRunStudio  2 роки тому

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

  • @McDonaldsSprite247
    @McDonaldsSprite247 10 місяців тому +1

    thank you

    • @NightRunStudio
      @NightRunStudio  10 місяців тому

      No problem! Glad to hear it was helpful.

  • @loofy8135
    @loofy8135 Рік тому

    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  Рік тому +1

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

    • @loofy8135
      @loofy8135 Рік тому

      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  Рік тому +1

      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 Рік тому +1

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

  • @tonoobforyouiv3783
    @tonoobforyouiv3783 Рік тому

    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  Рік тому

      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  Рік тому

      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 Рік тому

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

  • @KTIKNA
    @KTIKNA 8 місяців тому

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

  • @yoimhana76
    @yoimhana76 Рік тому

    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  Рік тому +1

      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).

  • @nyafnix7060
    @nyafnix7060 Рік тому +1

    i think its good
    !!

  • @shwooom8862
    @shwooom8862 10 місяців тому

    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  10 місяців тому

      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?

  • @druwayu
    @druwayu Рік тому

    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  Рік тому +1

      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

  • @thesossypus7347
    @thesossypus7347 Рік тому +1

    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 Рік тому +1

      @@NightRunStudio yup, i think that was it thanks

  • @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.

  • @CoreyBarlow
    @CoreyBarlow Рік тому +2

    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  Рік тому +4

      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 Рік тому +1

      @@NightRunStudio u the best

    • @gamdevgamdevpropro2781
      @gamdevgamdevpropro2781 Рік тому +1

      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

  • @laurengoodwin7652
    @laurengoodwin7652 Рік тому +1

    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  Рік тому +1

      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

  • @Crftedlover
    @Crftedlover 5 місяців тому

    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  5 місяців тому

      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!

  • @MCcrafaak
    @MCcrafaak 2 роки тому +4

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

  • @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.

  • @juliapaulewicz1471
    @juliapaulewicz1471 10 місяців тому

    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  10 місяців тому +1

      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!

  • @mikumikumilk9165
    @mikumikumilk9165 2 роки тому +2

    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  2 роки тому

      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  Рік тому +1

      @@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?

  • @brusty1260
    @brusty1260 2 роки тому +1

    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.

  • @jambon9613
    @jambon9613 Рік тому +1

    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

  • @japanlearneracc1126
    @japanlearneracc1126 Рік тому

    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  Рік тому

      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.

  • @acrow4969
    @acrow4969 8 місяців тому

    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  8 місяців тому

      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!

  • @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  Рік тому +1

      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!

  • @nee379
    @nee379 2 роки тому +2

    I cant quite seem to make 3D work

    • @NightRunStudio
      @NightRunStudio  2 роки тому +1

      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 2 роки тому +2

      @@NightRunStudio Alright thank you!

  • @readypanda5116
    @readypanda5116 2 роки тому

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

    • @NightRunStudio
      @NightRunStudio  2 роки тому

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

  • @harethkhoja3738
    @harethkhoja3738 Рік тому

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

    • @NightRunStudio
      @NightRunStudio  Рік тому

      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.

  • @_arcadian._
    @_arcadian._ 2 роки тому

    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  2 роки тому

      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._ 2 роки тому

      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._ 2 роки тому

      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  2 роки тому

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

    • @_arcadian._
      @_arcadian._ 2 роки тому

      @@NightRunStudio Yes, i checked with the debug

  • @mhd3117
    @mhd3117 9 місяців тому

    hi attach the script pleaseeeeeeeeeee

  • @CarlozYT
    @CarlozYT 2 роки тому

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

    • @NightRunStudio
      @NightRunStudio  2 роки тому +1

      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 2 роки тому

      ​@@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 2 роки тому

      @@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  2 роки тому +1

      @@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 2 роки тому +1

      @@NightRunStudio IT WORKS TYSM

  • @Stripho
    @Stripho 9 місяців тому

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

    • @NightRunStudio
      @NightRunStudio  9 місяців тому

      What error is it giving you?

    • @Stripho
      @Stripho 9 місяців тому

      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 Рік тому +1

      @@NightRunStudio Thanks this helped

  • @BomberManHipHop
    @BomberManHipHop Рік тому +1

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

    • @NightRunStudio
      @NightRunStudio  Рік тому +1

      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 Рік тому +1

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

  • @samchristian9149
    @samchristian9149 Рік тому +1

    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  Рік тому +1

      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  Рік тому +1

      @@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 Рік тому +1

      @@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 Рік тому +1

      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 Рік тому +1

    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  Рік тому +1

      @@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 Рік тому +1

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