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;
}
}
}