Richard Mcilwain
Richard Mcilwain

Reputation: 33

How do I use a void function using delegates?

I have been attempting to use event handling for a game's input. When seeing others use similar methods, they are able to add a void function to the delegate variable without an error. Whenever I try to add the Move() function to OnAxisChange, I receive 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();
            }
        } 
    }
}

The following 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 for event handling is still a bit foreign to me, so I assume I am misunderstanding something.

Upvotes: 3

Views: 756

Answers (1)

NtFreX
NtFreX

Reputation: 11367

You need to remove () after Move. Like that you are calling your method and try to add the return type of it which is nothing. Just change it to the following.

CharacterView.OnAxisChange += Move;

CharacterView.OnAxisChange -= Move;

Upvotes: 3

Related Questions