Search Unity

Question Health not decreasing

Discussion in 'Scripting' started by ahmadmuddassir635, Dec 18, 2023.

  1. ahmadmuddassir635

    ahmadmuddassir635

    Joined:
    Jul 16, 2023
    Posts:
    24
    i have written the below code but when the the bullet collides with anything only once the health decreases i have given the health three now it only comes to 2 and then repeating it again and again

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class Bullet : MonoBehaviour
    {
    public float life;
    public LayerMask touchable;

    private void Start()
    {
    }
    void Awake()
    {
    }



    void OnCollisionEnter(Collision collision)
    {

    if (collision.gameObject.CompareTag("Player"))
    {
    life -= 1;
    Debug.Log("Life: " + life);
    if (life <= 0.0f)
    {
    Destroy(collision.gameObject);
    }
    }
    Destroy(gameObject);
    }



    }
     

    Attached Files:

  2. RadRedPanda

    RadRedPanda

    Joined:
    May 9, 2018
    Posts:
    1,647
    You should use Code Tags when posting code in this forum.

    Second, it looks like your life is attached to your Bullet. I presume you want to instead be subtracting the Player's life, not the Bullet's life. If you have a Player script, you would need to GetComponent to grab that, and then change its life total.
     
  3. ahmadmuddassir635

    ahmadmuddassir635

    Joined:
    Jul 16, 2023
    Posts:
    24
    Please can you give me the code
     
  4. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,605
    Currently your bullet has health (life). You decrease that life when you collide with the player. Depending on the game concept, this could be a valid mechanic.. but you likely want to decrease the player health instead. If your player has a script that contains its HP, you should get that after verifying you hit the player:
    Code (CSharp):
    1. YourHealthScript playerHealth = collision.gameObject.GetComponent<YourHealthScript>()
    Further, consider whose responsibility certain actions are. What information is which object aware of, and whose responsibility is it to change those values? The bullet, for example, could have a damage attribute. But it should never directly access the players health. The player / player health class should be in control of what happens with its health value. You can add functions to make sure of that, or wrap the actual health variable in a property, or both. The bullet should then only call, for example, playerHealth.TakeDamage(myDamage). This function, internally, would make sure to destroy the player (and possibly play a death animation or something) when health reaches zero. The bullets have no business with any of that logic, and you should never have to change the bullet script because something about the player death logic needs to be adjusted.
     
  5. ahmadmuddassir635

    ahmadmuddassir635

    Joined:
    Jul 16, 2023
    Posts:
    24
    Give me the full code of playerhealth script
     
  6. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,658
    Send me a script / the scripts please!

    https://forum.unity.com/threads/question-complete-scripts-for-different-needs.1190314/#post-7614199



    The purpose of this forum is to assist people who are ready to learn by doing, and who are unafraid to get their hands dirty learning how to code, particularly in the context of Unity3D.

    This assumes you have at least written and studied some code and have run into some kind of issue.

    If you haven't even started yet, go check out some Youtube videos for whatever game design you have in mind. There are already many examples of the individual parts and concepts involved, as there is nothing truly new under the sun.

    If you just want someone to do it for you, you need go to one of these places:

    https://forum.unity.com/forums/commercial-job-offering.49/

    https://forum.unity.com/forums/non-commercial-collaboration.17/

    https://livehelp.unity.com/?keywords=&page=1&searchTypes=lessons

    Remember this is YOUR game, not ours. We have our own games we're working on.



    How to report your problem productively in the Unity3D forums:

    http://plbm.com/?p=220

    This is the bare minimum of information to report:

    - what you want
    - what you tried
    - what you expected to happen
    - what actually happened, log output, variable values, and especially any errors you see
    - links to actual Unity3D documentation you used to cross-check your work (CRITICAL!!!)

    The purpose of YOU providing links is to make our job easier, while simultaneously showing us that you actually put effort into the process. If you haven't put effort into finding the documentation, why should we bother putting effort into replying?



    If you post a code snippet, ALWAYS USE CODE TAGS:

    How to use code tags: https://forum.unity.com/threads/using-code-tags-properly.143875/

    - Do not TALK about code without posting it.
    - Do NOT post unformatted code.
    - Do NOT retype code. Use copy/paste properly using code tags.
    - Do NOT post screenshots of code.
    - Do NOT post photographs of code.
    - Do NOT attach entire scripts to your post.
    - ONLY post the relevant code, and then refer to it in your discussion.



    If you would like to debug and fix the code you have, try this approach:

    Time to start debugging!

    By debugging you can find out exactly what your program is doing so you can fix it.

    Here is how you can begin your exciting new debugging adventures:

    You must find a way to get the information you need in order to reason about what the problem is.

    Once you understand what the problem is, you may begin to reason about a solution to the problem.

    What is often happening in these cases is one of the following:

    - the code you think is executing is not actually executing at all
    - the code is executing far EARLIER or LATER than you think
    - the code is executing far LESS OFTEN than you think
    - the code is executing far MORE OFTEN than you think
    - the code is executing on another GameObject than you think it is
    - you're getting an error or warning and you haven't noticed it in the console window

    To help gain more insight into your problem, I recommend liberally sprinkling
    Debug.Log()
    statements through your code to display information in realtime.

    Doing this should help you answer these types of questions:

    - is this code even running? which parts are running? how often does it run? what order does it run in?
    - what are the names of the GameObjects or Components involved?
    - what are the values of the variables involved? Are they initialized? Are the values reasonable?
    - are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

    Knowing this information will help you reason about the behavior you are seeing.

    You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as
    Debug.Log("Problem!",this);


    If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

    You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

    You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

    You could also just display various important quantities in UI Text elements to watch them change as you play the game.

    Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer for iOS: https://forum.unity.com/threads/how-to-capturing-device-logs-on-ios.529920/ or this answer for Android: https://forum.unity.com/threads/how-to-capturing-device-logs-on-android.528680/

    If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

    Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

    If your problem is with OnCollision-type functions, print the name of what is passed in!

    Here's an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

    https://forum.unity.com/threads/coroutine-missing-hint-and-error.1103197/#post-7100494

    If you are looking for how to attach an actual debugger to Unity: https://docs.unity3d.com/2021.1/Documentation/Manual/ManagedCodeDebugging.html

    "When in doubt, print it out!(tm)" - Kurt Dekker (and many others)

    Note: the
    print()
    function is an alias for Debug.Log() provided by the MonoBehaviour class.
     
    Yoreki likes this.
  7. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,605
    If you have a specific problem we can talk about that, but this is a perfect beginner task to complete.
    Kurt said everything else i would have to say on this topic.

    Also, it wouldnt change my reply, but "please".
     
  8. ahmadmuddassir635

    ahmadmuddassir635

    Joined:
    Jul 16, 2023
    Posts:
    24
    Yes i know that you would be working on your own games because on unity forum everyone is a gamedeveloper but i have practiced so many scripts about player health but it is not working so if you can give me the code that i would be very thankful to you please.
     
  9. ahmadmuddassir635

    ahmadmuddassir635

    Joined:
    Jul 16, 2023
    Posts:
    24
    But i need it
     
  10. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,605
    You want to make a game. To make that wish come true, you need to understand how this works. Us spoon feeding you code does not help you, it simply delays your problem and makes you face even worse issues you wont be able to overcome on your own. Take a step back. Do tutorials. Dont just type, understand what each line does. If you dont understand something, look up what the functions involved do, until you understand it. There is no short cut to learning.

    If throughout all of this you have a problem you cannot resolve, or a question you cant find an answer to, that's what the forum is for. If you tell us what your problem is, we can explain to you how to approach the issue at hand. I gave you such an explanation. If there is an issue with it you have not stated that. If not, what is your problem with implementing it? Look at it step by step. Break it down. Which part is it you have troubles with?

    If this is not about learning to you, but you really just need the code, then Kurt already left you links to placed where you can pay people to code for you.
     
  11. ahmadmuddassir635

    ahmadmuddassir635

    Joined:
    Jul 16, 2023
    Posts:
    24
    Hello you are like my teacher so SIR i have given the script code and i have mentioned the problem at the top so what can i do with that so see that problem and reply me if you learn about that problem then tell me your own and you do not solve it than tell me some other people and also you do this question because you have everywhere account so please SIR.
     
  12. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,415
    Whilst it is up to individuals on how much time they wish to spend helping, the forums are NOT here to teach you the fundamentals on how to use Unity nor write code for you. That is the place for tutorials. Don't ask for code to be written for you.

    If you have a specific question then you can be helped but it's often the case that the dev asking the question doesn't understand the answer because of a lack of understanding of the subject in question.

    I would advise that you understand the meaning of each line of code you write and how to use the systems you're touching. This can be done with tutorials, small experiments with each (etc).
     
    Lurking-Ninja and Yoreki like this.
  13. ahmadmuddassir635

    ahmadmuddassir635

    Joined:
    Jul 16, 2023
    Posts:
    24
    I know every line of code but how can i solve the problem.
     
  14. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,415
    You were replied to above and your reply was:
    You are clearly asking for code and not how to solve a problem.
     
  15. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,415
    So you already know that OnCollisionEnter will only be called once when two colliders come into contact?

    Could you explain what this means? Please explain in detail what you're expecting to happen with regards to the bullet/life and please be consistent and accurate; you mention "health" and I see a "life" field; I assume they are the same thing? You're not referring to the player "health" here I presume.
     
    Yoreki likes this.
  16. ahmadmuddassir635

    ahmadmuddassir635

    Joined:
    Jul 16, 2023
    Posts:
    24
    I mean that the health is not decreasing correctly.
     
  17. ahmadmuddassir635

    ahmadmuddassir635

    Joined:
    Jul 16, 2023
    Posts:
    24
    It means that when i write the destroy(gameobject) inside the if(life<=0) then the life is decreasing correctly but when i have written it like this that i have given then i have given the life 3 then it only comes to 2 and the 2 repeats on every collision and the player is not destroying.
     
  18. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,415
    This was a question btw.

    Because you are not editing your post to use code-tags, here's your code:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Bullet : MonoBehaviour
    6. {
    7.     public float life;
    8.     public LayerMask touchable;
    9.  
    10.     private void Start()
    11.     {
    12.     }
    13.     void Awake()
    14.     {
    15.     }
    16.  
    17.     void OnCollisionEnter(Collision collision)
    18.     {
    19.  
    20.         if (collision.gameObject.CompareTag("Player"))
    21.         {
    22.             life -= 1;
    23.             Debug.Log("Life: " + life);
    24.             if (life <= 0.0f)
    25.             {
    26.                 Destroy(collision.gameObject);
    27.             }
    28.         }
    29.         Destroy(gameObject);
    30.     }
    31. }
    So, ignoring "touchable" which does nothing, when this "bullet" first hits anything it'll check to see if it hits a Collider where the GameObject has a tag of "Player". If so, it'll reduce the bullet life by 1 (int) even though you've set it to be a float for some reason. If the life of the bullet is <= 0 then it'll destroy what you hit (the "player" GameObject). TBH, that makes little sense to me; why should you only destroy what you hit when the life of the bullet is <=0?

    Anyway, then in all cases no matter what it hits, it'll destroy the bullet so it was pointless reducing the life of the bullet as you're always destroying the bullet whenever it contacts anything.

    All I've done is go through each line but you already said you understand what each line does which is clearly not true so maybe you can explain what it is you want to happen with regards to the "player" and the "bullet" and this "life" property of the "bullet".
     
    Yoreki likes this.