Write ray hit behaviour on gameObject being hit

Hello,

I’m doing a classic gun shooting a ray for a game. I want a way to handle the hit objects differently depending on their type, (NPC, dynamic objects, environment etc), which leads to a lot of code on the gun class.

I am looking for a way to simply detect if the ray hit something, then invoke a function on that object, with the RaycastHit information passed as a parameter.

I’ve added a ‘handler’ script that objects being hit will have, and that will point to a specific method on the object.

The issue I have is that I can’t pass the raycasthit as a parameter using Invoke(), and I can’t use a coroutine as I get this error in the HitHandler:
Non-invocable member 'name' cannot be used like a method.

On the gun

    public void Shoot ()
    {
        RaycastHit hit;
        if (Physics.Raycast(barrelPoint.transform.position, barrelPoint.transform.forward, out hit))
        {
            try
            {
                hit.transform.gameObject.GetComponent<HitHandler>().CallHitMethod(); // Want to pass hit as parameter here, which works.

            }
            catch (Exception e)
            {
                Debug.Log(e);
            }
        }

My hit handler. The method to be called is inserted via the editor.

public class HitHandler : MonoBehaviour
{
    [SerializeField]
    UnityEvent OnHit;

    public void CallHitMethod()
    {
        OnHit.Invoke(); // Want to pass hit as parameter here, which doesn't work. Also tried coroutine.
    }
}

The above handler would point to this class & function, where I’d handle the hit.

public class Target : MonoBehaviour
{
    void OnBulletHit ()
    {
        Debug.Log("Ouch");
    }
}

Have I got something for you my friend… you are gonna LOVE this stuff. In fact, when I first learned about this stuff, I made the same exact gesture you are making in your avatar: pew pew pew!

Using Interfaces in Unity3D:

https://discussions.unity.com/t/797745/2

https://discussions.unity.com/t/807699/2

Check Youtube for other tutorials about interfaces and working in Unity3D. It’s a pretty powerful combination.

1 Like

Kurt-Dekker, you beauty. That worked great! Thanks.

1 Like