如何使此代码更容易管理碰撞音频?

时间:2012-12-07 19:57:25

标签: c# optimization audio refactoring unity3d

我只是在寻找能够使这段代码变得更好的任何建议。如果我以这种方式继续前进将会是一些我认为可以避免的代码,但是这样做的方法现在超出了我的范围。这将很快失去控制。

public enum PhysicMaterialType
{
    SoundFailure = 0,

    AsteroidBall,

    BalloonRubber
}

public void PlaySoundBasedOnCollision ( PhysicMaterialType phyMatA, PhysicMaterialType phyMatB )
{
    switch ( phyMatA )
    {
        case PhysicMaterialType.AsteroidBall:
            {
                CheckAsteroidBallCollision ( phyMatB );

                break;
            }
        case PhysicMaterialType.BalloonRubber:
            {
                CheckBalloonRubberCollision ( phyMatB );

                break;
            }
   }

}

void CheckAsteroidBallCollision ( PhysicMaterial phyMatB )
{
    switch ( phyMatB )

    {
        case PhysicMaterialType.AsteroidBall:
            {
                //Play AsteroidAsteroidBallSound

                break;
            }
        case PhysicMaterialType.BalloonRubber:

            {
                break;
            }
   }
}

1 个答案:

答案 0 :(得分:1)

如果您将拥有许多类型,并且必须以各种方式处理不同类型之间的预期碰撞声音,请考虑从PhysicMaterial为您要实现的每种类型派生一个类。在派生类中定义一个公共方法来处理确定要播放的声音 - 将第二个对象的类型传递给此方法。像这样:

class PhysicMaterial
{
   public virtual string GetCollisionSound (PhysicMaterialType targetType)
   {
       // define default behavior here, if derived class doesn't need to do anything special
   }
}

class AsteroidBall : PhysicMaterial
{
   public override string GetCollisionSound (PhysicMaterialType targetType)
   {
       ...
   }
}

class BalloonRubber: PhysicMaterial
{
   public override string GetCollisionSound (PhysicMaterialType targetType)
   {
       ...
   }
}

返回最适合您的方案的任何数据类型。