我有单独的跳跃和运行类(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/