No damage taken code isn't working.


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?

        if (gameObject.tag == "Player")
        {
            if (Input.GetKeyDown(KeyCode.LeftShift))
            {
                gameObject.tag = "Enemy";
                canAttack = 0f;
            }
        }

Full script-

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

public class EnemyMovement : MonoBehaviour
{
    public float speed = 3f;
    [SerializeField] private float attackDamage = 10f;
    [SerializeField] private float attackSpeed = 1f;
    public float canAttack;
    private Transform target;
    CircleCollider2D collision;

    private void Update() {
        if (target != null) {
            float step = speed * Time.deltaTime;
            transform.position = Vector2.MoveTowards(transform.position, target.position, step);
        }

        if (gameObject.tag == "Player")
        {
            if (Input.GetKeyDown(KeyCode.LeftShift))
            {
                gameObject.tag = "Enemy";
                canAttack = 0f;
            }
        }

    }

    private void OnCollisionStay2D(Collision2D other) {
        if (other.gameObject.tag == "Player") {
            Debug.Log("I hit the player");
            if (attackSpeed <= canAttack) {
            other.gameObject.GetComponent<PlayerHealth>().UpdateHealth(-attackDamage);
            canAttack = 0f;
            } else {
                canAttack += Time.deltaTime;
            }
               
        }
    }


    private void OnTriggerEnter2D(Collider2D other) {
        if (other.gameObject.tag == "Player") {
            target = other.transform;
        }
    }

    private void OnTriggerExit2D(Collider2D other)
    {
        if (other.gameObject.tag == "Player")
        {
            target = null;
        }
    }



}

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://discussions.unity.com/t/700551 or this answer for Android: https://discussions.unity.com/t/699654

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://discussions.unity.com/t/839300/3

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

1 Like

According to Unity - Scripting API: Input.GetKeyDown, 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().

It didn’t work, damage is still being dealt

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.

1 Like

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.

your programming style is a little cluttered and unclear.

theres a couple things you want, a flag

//  flag to deal damage
public bool canBeDamaged = true;

the enemy checking player can be damaged

// in your enemy
public Player player;
private PlayerHealth playerHealth;

private void Start()
{

    if(player == null)
    {
        Debug.LogError("Player is NULL");
        Debug.Break();
    }

    playerHealth = player.GetComponent<PlayerHealth>();

}

private void DealDamage()
{
    if( player.canBeDamaged )
        player.TakeDamage(value);

    // you dont need an else
}

a take damage function

// back in your player health
public void TakeDamage(float damage)
{
    myHealth -= damage;
}

a function to change canBeDamaged

// in your player health
private void Update()
{
    // GetKey is true while key is down, GetKeyDown is only true when the key is pressed down once.
    if( Input.GetKey(Keycode.LeftShift) )
        canBeDamaged = false;
    else
        canBeDamaged = true;

}

this code is not tested but i’m sure you get the idea.

1 Like

Alright calm down, was only asking for help

Alright, i’ll have a look at this. Thank you!

And i provided help and feedback as best as i could with the given information.
Why do you tell me to calm down?