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