- Home /
Argument 1: cannot convert from 'method group' to 'UnityAction'
I have the UnityAction < RaycastHit > onHitEvent:
public class RaycastTrigger: MonoBehaviour
{
public void ReceiveRaycast(RaycastHit hit)
{
RaycastEventTrigger(hit);
}
[Serializable]
public class OnRaycastHit: UnityEvent<RaycastHit> { }
[SerializeField]
private OnRaycastHit onRaycastHitEvent = new OnRaycastHit();
public OnRaycastHit onHitEvent { get { return onRaycastHitEvent; } set { onRaycastHitEvent = value; } }
public void RaycastEventTrigger(RaycastHit hit)
{
onHitEvent.Invoke(hit);
}
}
It invokes when my raycast hits an object with a RaycastTrigger component attached, and passes the raycast hit information onwards. But sometimes I don't need the raycast information, I just want to trigger a generic event by hitting it with a raycast:
void Start()
{
GetComponent<RaycastTrigger>().onHitEvent.AddListener(MyClick);
}
public void MyClick()
{
...
}
When this code is compiled, though, I get the compile error 'Argument 1: cannot convert from 'method group' to 'UnityAction<RaycastHit>'
If I'm using the editor I can use the event editor in the inspector to select Click() in the dropdown menu under static parameters, so I know it must be possible to do via script. Do I need to add static parameters with something besides for a call to AddListener()? I can always just make Click take (RaycastHit hit) as a parameter and then not use it, but that seems wasteful.
Answer by Hellium · Jul 17, 2019 at 07:17 PM
Either declare MyClick
as follow (even if you don't need the parameter)
public void MyClick( RaycastHit hit )
{
}
Use a lambda method
void Start()
{
GetComponent<RaycastTrigger>().onHitEvent.AddListener( raycastHit => MyClick() );
}
Or declare another function as callback, which calls MyClick
void Start()
{
GetComponent<RaycastTrigger>().onHitEvent.AddListener( OnHitEvent );
}
public void OnHitEvent( RaycastHit raycastHit )
{
MyClick();
}
public void MyClick()
{
...
}