c# - 是不是不能使用父类的事件呢?

标签 c# visual-studio unity-game-engine

我有单独的跳跃和运行类(class)。可能还有其他可动画化的 Action ,比如攀爬、飞行,谁知道我会想出什么。因此,让所有这些运动类继承一个名为 AnimatableMovement 的类是有意义的。它的唯一目的是设置事件。

请考虑:

public class AnimatableMovement : MonoBehaviour
{
    public event AnimationStateDelegate OnAnimationStateChange;
    public delegate void AnimationStateDelegate(string newState);
}

然后步行:

public class Movement : AnimatableMovement
{
    public float speed = 5f;
    protected Rigidbody2D body;

    void Start()
    {
        body = transform.GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        float horizontalInput = Input.GetAxis("Horizontal");

        if (horizontalInput != 0)
        {
            body.velocity = new Vector2(horizontalInput * speed, body.velocity.y);
            OnAnimationStateChange?.Invoke("walk");
        } else
        {
            OnAnimationStateChange?.Invoke("idle");
        }
    }
}

如果委托(delegate)与运动在同一个类中定义,一切都会像魅力一样工作,但违反了 DRY 原则,因为我必须将相同的两行复制/粘贴到每个运动类型类。所以我认为这将是一个显而易见的解决方案,但是这样做,分成两个类,我得到一个错误:

Assets\Scripts\Movement.cs(30,13): 错误 CS0070: 事件“AnimatableMovement.OnAnimationStateChange”只能出现在 += 或 -= 的左侧(除非在输入“AnimatableMovement”)

最佳答案

尝试这种方法:

public abstract class AnimatableMovement 
{
    public event EventHandler<string> AnimationStateChange;
    
    protected void RaiseAnimationStateChangeEvent( string newState )
    {
        this.AnimationStateChange?.Invoke( this, newState );
    }
}

还有:

public class Movement : AnimatableMovement
{
    public float speed = 5f;
    protected Rigidbody2D body;

    void Start()
    {
        body = transform.GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        float horizontalInput = Input.GetAxis("Horizontal");

        if (horizontalInput != 0)
        {
            body.velocity = new Vector2(horizontalInput * speed, body.velocity.y);
            RaiseAnimationStateChangeEvent("walk");
        } else
        {
            RaiseAnimationStateChangeEvent("idle");
        }
    }
}

关于c# - 是不是不能使用父类的事件呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72829339/

相关文章:

unity-game-engine - 如何根据玩家的旋转方式为轴添加值?

c# - 双重乘法给出 NaN

c# - WCF 的流传输限制

c# - 另一个使用 StreamWriter 的进程正在使用的文件

c# - 在向项目添加新项目时,Visual Studio 2022 版本 17.4.1 不支持选项卡配置

visual-studio - Visual Studio 9.0 错误 C2051 大小写表达式不是常量

c# - Windows 窗体和 C# 中控件的动态自上而下列表?

visual-studio - 如何使用本地文件夹中的 nuget 符号包进行调试?

c# - Admob 横幅广告在 Unity3D 中无法正常工作

ios - Unity ios 错误生成 GameSparksWebSocket.h 文件未找到 GSExternal.m