Home > Software design >  Deal damage to an object while using Raycast
Deal damage to an object while using Raycast

Time:12-16

I've created an object and I've added a health bar, but when I want to shoot while using RayCast it stops the game. I don't know what can I do more or change. I don't want to create projectiles/balls to shoot.

So this is EnemyHealth assigned to Enemy object:

public class EnemyHealth : MonoBehaviour
{
    public float maxHealth = 100f;
    public float health;

    void Start()
    {
        health = maxHealth;
    }
    
    public void TakeDamage(float damageAmount)
    {
        health -= damageAmount;
        if(health <= 0)
        {
            Destroy(gameObject);
        }
    }
}

And this is code where I shoot and take dmg:

public class HitEnemy : MonoBehaviour
{
    [SerializeField] Camera cam;
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = cam.ViewportPointToRay(new Vector3(0.5f, 0.5f));
            if (Physics.Raycast(ray, out RaycastHit hit))
            {
                gameObject.GetComponent<EnemyHealth>().TakeDamage(10);
            }
        }
    }     
}

Component Enemy is blank, because I don't know what can I add more.

CodePudding user response:

  1. you need to check if the ray is hitting an enemy then take damage
  2. without checking you're looking for enemy script in maybe a wall and that's why it's giving an error
void Update()
        {
            if (Input.GetMouseButtonDown(0))
            {
                Ray ray = cam.ViewportPointToRay(new Vector3(0.5f, 0.5f));
                if (Physics.Raycast(ray, out RaycastHit hit))
                {
                    if (hit.collider.GetComponent<EnemyHealth>().enabled)
                    {
                        gameObject.GetComponent<EnemyHealth>().TakeDamage(10);
                        
                    }
                    else
                    {
                        Debug.Log("No Enemy in sight, Ray is touching : "   hit.collider.name);
                    }
                }
            }
            
        }

CodePudding user response:

It looks like you're trying to get EnemyHealth that's attached to the gaeObject. The problem with that is, you're looking for EnemyHealth on the (presumably) player controller object, not the enemy object.

Let's look at a possible solution:

void Update ( )
{
    if ( Input.GetMouseButtonDown ( 0 ) )
    {
        // Check to see if a RayCast hits an object.
        if ( Physics.Raycast ( cam.ViewportPointToRay ( new Vector3 ( 0.5f, 0.5f ) ), out var hit, cam.farClipPlane ) )
        {
            // Check to make sure the hit object has an 'EnemyHealth' component.
            if ( hit.transform.TryGetComponent<EnemyHealth> ( out var enemyHealth ) )
            {
                enemyHealth.TakeDamage ( 10 );
            }
        }
    }
}
  • Related