Can someone please help me , ive been beating my head at this for over 2 hours

I’m trying to make a sword thing where, when the player presses V and a enemy is in front of him, it gives the enemy damage, but the raycast doesn’t register on the enemy, and the enemy is on the correct layer and tag

using UnityEngine;
public class Sword_Player : MonoBehaviour
{
    private EnemyHealth EnemyHPscript;
    public Transform PlayerTR;
    public int sworddamage;
    public int raydistance;
    public LayerMask enemyLayer;
    private void FixedUpdate()
    {
        if (Input.GetKeyDown(KeyCode.V))
        {
            RaycastHit2D hit = Physics2D.Raycast(transform.position, PlayerTR.right, enemyLayer, raydistance);
            Debug.DrawRay(transform.position, new Vector3(PlayerTR.position.x + 100f, PlayerTR.position.y, PlayerTR.position.z), Color.red);
            if (hit.collider.tag == "Enemy")
            {
                Debug.Log("it hit");
                EnemyHPscript = hit.collider.GetComponent<EnemyHealth>();
                EnemyHPscript.TakeDamage(sworddamage);
            }
        }
    }
}

and this is the enemyHP script:

using UnityEngine;
public class EnemyHealth : MonoBehaviour
{
    public float MaxHP;
    private float CurrentHP;
    public float timeB4destroyGO;
    private void Start()
    {
        CurrentHP = MaxHP;
    }
    public void TakeDamage(int damage)
    {
        CurrentHP -= damage;
        if(CurrentHP <= 0) { Die(); }
    }
    public void Die()
    {
        Destroy(gameObject , timeB4destroyGO);
    }
}

You didn’t say what the problem is. What’s not working? Are you getting runtime errors?

1 Like
  • the title of your thread should describe your problem,
  • the content of your post should also describe your problem.

Right now, nobody will bother studying your scripts to find out what is wrong with them.

1 Like

raycast can return null, that can cause error messages,
this example checks if hit is not null