Unity 3D Raycast mouse shooting

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

public class Shoot : MonoBehaviour
{

    GameObject hitObject;

    private void Update()
    {
        if (Input.GetMouseButtonDown(0) && hitObject)
        {
            Debug.Log(hitObject.name);
            IDamagable damagable = hitObject.GetComponentInParent<IDamagable>();
            damagable?.Damage(10);
        }
    }
    void FixedUpdate()
    {
        Vector3 fwd = transform.TransformDirection(Vector3.forward);

        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit, 100))
        {
            hitObject = hit.transform.gameObject;
        }

    }


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

public interface IDamagable
{
    public void Damage(int damage);
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Chest : MonoBehaviour, IDamagable
{
    public void Damage(int damage)
    {
        print("Chest hit -10");
    }

}
Scroll to Top