Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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");
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading