- Home /
Method doesn't get implemented after subscribing to Func
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, or the event isn't even being invoked. I don't have any compile errors.
Normally you would start a coroutine with StartCoroutine, not Invoke so i'm not sure if this can work.
It works. I've had coroutines subscribe to funcs before. The only difference is that this coroutine takes in an argument.
I owe you an apology: I changed
OnFire.Invoke(mousePosition);
to
StartCoroutine(OnFire(mousePosition));
Works perfectly now.
No apology necessary, I learned something new as well.
Answer by sean244 · May 24, 2018 at 05:41 AM
I changed
OnFire.Invoke(mousePosition);
to
StartCoroutine(OnFire(mousePosition));
Works perfectly now.