unity3d Unity错误-“无法将类型'void'隐式转换为'System.Action(“

toiithl6  于 2023-03-19  发布在  其他
关注(0)|答案(1)|浏览(267)

我试着给一个动作添加函数,它们没有参数。我不明白为什么我不能添加函数。第一部分创建和调用动作。

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

第二个脚本将功能添加到动作中。

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

g6ll5ycj1#

Hit()

在执行此行时,我已经执行了该方法,并尝试分配“返回值”-但它返回void,因此无法将其分配/添加到您的Action
你想

player.OnHitAction += Hit;

它引用方法但不执行它

相关问题