In Unity, I have the following script which contains a func that takes in a Vector2 as an argument and returns IEnumerator
using System;
using System.Collections;
using UnityEngine;
public class Weapon : MonoBehaviour
{
public static event Func<Vector2, IEnumerator> OnFire;
private void OnMouseDown()
{
Fire();
}
private void Fire()
{
Vector2 mousePosition = new Vector2(Camera.main.ScreenToWorldPoint(Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y);
if (OnFire != null)
{
OnFire.Invoke(mousePosition);
}
}
}
In my other script, I have a Coroutine that subscribes to that method
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour
{
private void Start()
{
Weapon.OnFire += ShootAt;
}
private IEnumerator ShootAt(Vector2 target)
{
yield return new WaitForSeconds(.5f);
print("Shot at " + target);
}
private void OnDestroy()
{
Weapon.OnFire -= ShootAt;
}
}
But the ShootAt method in my Bullet script never gets called. It's as if it's not even subscribing to the event. I don't have any compile errors.
The ShootAt function you are subscribing to the OnFire event is not a normal function. It's a coroutine function which requires the use of StartCoroutine to call it. Put your OnFire.Invoke call inside the StartCoroutine function and it should work.
Replace
OnFire.Invoke(mousePosition);
with
StartCoroutine(OnFire.Invoke(mousePosition));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With