Search Unity

No damage taken code isn't working.

Discussion in 'Scripting' started by EdwardMollan, May 13, 2022.

  1. EdwardMollan

    EdwardMollan

    Joined:
    May 4, 2022
    Posts:
    9

    I'm trying to make it so my enemy can't deal damage when the player is holding down left shift, does anyone know why this code isn't working?

    Code (CSharp):
    1.         if (gameObject.tag == "Player")
    2.         {
    3.             if (Input.GetKeyDown(KeyCode.LeftShift))
    4.             {
    5.                 gameObject.tag = "Enemy";
    6.                 canAttack = 0f;
    7.             }
    8.         }

    Full script-
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class EnemyMovement : MonoBehaviour
    6. {
    7.     public float speed = 3f;
    8.     [SerializeField] private float attackDamage = 10f;
    9.     [SerializeField] private float attackSpeed = 1f;
    10.     public float canAttack;
    11.     private Transform target;
    12.     CircleCollider2D collision;
    13.  
    14.     private void Update() {
    15.         if (target != null) {
    16.             float step = speed * Time.deltaTime;
    17.             transform.position = Vector2.MoveTowards(transform.position, target.position, step);
    18.         }
    19.  
    20.         if (gameObject.tag == "Player")
    21.         {
    22.             if (Input.GetKeyDown(KeyCode.LeftShift))
    23.             {
    24.                 gameObject.tag = "Enemy";
    25.                 canAttack = 0f;
    26.             }
    27.         }
    28.  
    29.     }
    30.  
    31.     private void OnCollisionStay2D(Collision2D other) {
    32.         if (other.gameObject.tag == "Player") {
    33.             Debug.Log("I hit the player");
    34.             if (attackSpeed <= canAttack) {
    35.             other.gameObject.GetComponent<PlayerHealth>().UpdateHealth(-attackDamage);
    36.             canAttack = 0f;
    37.             } else {
    38.                 canAttack += Time.deltaTime;
    39.             }
    40.                
    41.         }
    42.     }
    43.  
    44.  
    45.     private void OnTriggerEnter2D(Collider2D other) {
    46.         if (other.gameObject.tag == "Player") {
    47.             target = other.transform;
    48.         }
    49.     }
    50.  
    51.     private void OnTriggerExit2D(Collider2D other)
    52.     {
    53.         if (other.gameObject.tag == "Player")
    54.         {
    55.             target = null;
    56.         }
    57.     }
    58.  
    59.  
    60.  
    61. }
    62.  
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,735
    Nope, but here's how you can track it down:

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

    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.

    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 or 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/

    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.

    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

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

    One thing I'd ask yourself is "why is something that was tagged as player now going to be tagged as enemy?" (your first block of code).
     
    Yoreki likes this.
  3. kru

    kru

    Joined:
    Jan 19, 2013
    Posts:
    452
    According to https://docs.unity3d.com/ScriptReference/Input.GetKeyDown.html, GetKeyDown returns true only on the frame when the user starts pressing the button.

    Since you want to query whether the using is holding the key down at the time that they take damage, consider using Input.GetKey() rather than Input.GetKeyDown().
     
  4. EdwardMollan

    EdwardMollan

    Joined:
    May 4, 2022
    Posts:
    9
    It didn't work, damage is still being dealt
     
  5. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,735
    Let us know when you actually do some debugging, otherwise everybody is just guessing. Good luck!

    Also, you may wish to answer the question at the bottom of my post above. It seems suspicious you are doing that.
     
    Yoreki likes this.
  6. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,605
    Your "EnemyMovement" script checks if the gameobject it's on has the player tag.. and if so assigns the enemy tag.

    Like, what the actual F are you trying to do? Why does your player seemingly have an EnemyMovement script? Why are you trying to turn your player into an enemy to not make him take damage, instead of simply preventing him from taking damage in the first place. This seems like increadibly convoluted spaghetti code.

    Try to think more modular. Your player should have a, say, Player script. This script would among other things have an HP property. HP being a property lets you easily control its getting and setting via code. Introduce some invincibility bool which you set to true if the player picks up an invincibility drug, or whatever, and simply make it so HP cant decrease while you have that active. Done.
    Enemies colliding with something now simply check if the other object has a player component and if so, try to apply their damage. Which wont do anything if the player is invincible.

    That is just one of a million ways to handle invincibilities. I never implemented one and that was the first thing that came to my mind. If you google for it, you will likely find more sophisticated solutions. Either way, if you want people to tell you why your code is not working, it would be a great idea to explain how your code is supposed to work in the first place.
     
  7. SourGummi

    SourGummi

    Joined:
    Nov 14, 2021
    Posts:
    96
    your programming style is a little cluttered and unclear.

    theres a couple things you want, a flag
    Code (CSharp):
    1. //  flag to deal damage
    2. public bool canBeDamaged = true;
    the enemy checking player can be damaged
    Code (CSharp):
    1. // in your enemy
    2. public Player player;
    3. private PlayerHealth playerHealth;
    4.  
    5. private void Start()
    6. {
    7.  
    8.     if(player == null)
    9.     {
    10.         Debug.LogError("Player is NULL");
    11.         Debug.Break();
    12.     }
    13.  
    14.     playerHealth = player.GetComponent<PlayerHealth>();
    15.  
    16. }
    17.  
    18. private void DealDamage()
    19. {
    20.     if( player.canBeDamaged )
    21.         player.TakeDamage(value);
    22.  
    23.     // you dont need an else
    24. }
    a take damage function
    Code (CSharp):
    1. // back in your player health
    2. public void TakeDamage(float damage)
    3. {
    4.     myHealth -= damage;
    5. }
    a function to change canBeDamaged
    Code (CSharp):
    1. // in your player health
    2. private void Update()
    3. {
    4.     // GetKey is true while key is down, GetKeyDown is only true when the key is pressed down once.
    5.     if( Input.GetKey(Keycode.LeftShift) )
    6.         canBeDamaged = false;
    7.     else
    8.         canBeDamaged = true;
    9.  
    10. }
    this code is not tested but i'm sure you get the idea.
     
    Johan_Liebert123 likes this.
  8. EdwardMollan

    EdwardMollan

    Joined:
    May 4, 2022
    Posts:
    9
    Alright calm down, was only asking for help
     
  9. EdwardMollan

    EdwardMollan

    Joined:
    May 4, 2022
    Posts:
    9
    Alright, i'll have a look at this. Thank you!
     
  10. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,605
    And i provided help and feedback as best as i could with the given information.
    Why do you tell me to calm down?