How do I use the void function using delegates?

I am trying to use event handling for game input. When other people use similar methods, they can add void function to the delegate variable without error. Whenever I try to add the Move () function to OnAxisChange, I get the following error:

Cannot implicitly convert type 'void' to 'CharacterView.InputAction'

public class CharacterView : MonoBehaviour {
    public delegate void InputAction();
    public static event InputAction OnAxisChange;

    public Vector2 InputAxis
    {
        get
        {
            float x = Input.GetAxisRaw("Horizontal");
            float y = Input.GetAxisRaw("Vertical");
            return (new Vector2(x, y));
        }
    }

    private void Update()
    {

        Vector2 input = InputAxis;
        if (input.x != 0 || input.y != 0)
        {
            if (OnAxisChange != null)
            {
                OnAxisChange();
            }
        } 
    }
}

      

Below is the class that handles the event.

public class CharacterController : MonoBehaviour {

    private void OnEnable()
    {
        CharacterView.OnAxisChange += Move();
    }
    private void OnDisable()
    {
        CharacterView.OnAxisChange -= Move();
    }

    public void Move()
    {
        Debug.Log("Entered the move function!");
    }

}

      

Using delegates to handle events is still a bit foreign to me, so I guess I am missing something.

+3


source to share


1 answer


You need to delete ()

after Move

. Likewise, you call your method and try to add a return type, which is nothing. Just change it to the following.



CharacterView.OnAxisChange += Move;

CharacterView.OnAxisChange -= Move;

      

+3


source







All Articles