Unity error – "Cannot implicitly convert type 'void' to 'System.Action("

I try to add function to an action, they don’t have parametrs. I don’t understand why i can’t add function.
First sctipt which creates and invokes action.

using UnityEngine;
using System;

public class Player : MonoBehaviour
{
    [SerializeField] private int _health;

    private int _currentHealth;

    public event Action OnHitAction;

    public void TakeDamage(int damage)
    {
        _currentHealth -= damage;

        if (_currentHealth <= 0)
        {
            //Die?.Invoke();
        }
        else
        {
            OnHitAction?.Invoke();
        }
    }
}

Second script adds function to action.

using UnityEngine;

public class PlayerAnimator : MonoBehaviour
{
    private Animator _animator;
    private PlayerMover _playerMover;

    private void Start()
    {
        Player player = new();
        player.OnHitAction += Hit();// Error is here
        _playerMover = GetComponent<PlayerMover>();
        _animator = GetComponent<Animator>();
    }
    private void Hit()
    {
        _animator.SetTrigger("Hit");
    }
}

>Solution :

Hit()

already executes the method when this line is executed and tries to assign the "return value" – but it returns void so it can’t be assigned / added to your Action

You want

player.OnHitAction += Hit;

which refers to the method but doesn’t execute it

Leave a Reply