我试图让我的 Unity 游戏代码尽可能健壮,理想情况下我希望能够在游戏启动之前抛出异常,例如在编译时,如果 Unity Inspector 参数丢失或不正确(例如 null或超出范围)。
Attributes目前我正在使用和UnityEngine.Assertionson的组合Awake()来检查空引用或不正确的值;在游戏启动时抛出异常(而不是在执行过程中的意外点),例如:
public class PlayerMovement : MonoBehaviour
{
[SerializeField]
[Tooltip("Rigidbody of the Player.")]
private Rigidbody playerRigidBody;
[SerializeField]
[Tooltip("Forward force of the Player.")]
[Range(100f, 50000f)]
private float forwardForce = 6000f;
[SerializeField]
[Tooltip("Sideways force of the Player.")]
[Range(10f, 1000f)]
private float sidewaysForce = 120f;
private GameManager gameManager;
void Awake()
{
// Cache essential references
gameManager = GameObject.FindGameObjectWithTag("GameManager").GetComponent<GameManager>();
// Assert that all required references are present and correct
UnityEngine.Assertions.Assert.IsNotNull(gameManager, "Member \"gameManager\" is required.");
UnityEngine.Assertions.Assert.IsNotNull(playerRigidBody, "Member \"Rigidbody\" is required.");
//UnityEngine.Assertions.Assert.IsTrue(ForwardForce > 100, "\"ForwardForce\" must be greater than 100");
//UnityEngine.Assertions.Assert.IsTrue(SidewaysForce > 10, "\"SidewaysForce\" must be greater than 10");
}
...
}
这是最佳实践,还是有更好的方法在游戏启动前验证基本参数?
皈依舞
相关分类