【发布时间】:2019-06-16 10:57:15
【问题描述】:
我正在努力使我的 Unity 游戏代码尽可能健壮,理想情况下,我希望能够在游戏启动之前抛出异常,例如在编译时,如果 Unity Inspector 参数丢失或不正确(例如 null 或超出范围)。
目前我在Awake() 上使用Attributes 和UnityEngine.Assertions 的组合来检查空引用或不正确的值;在游戏启动时抛出异常(而不是在执行期间的意外点),例如:
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");
}
...
}
这是最佳做法,还是有更好的方法在游戏启动前验证基本参数?
【问题讨论】:
-
为什么编译时需要做呢?每次更改变量时,您都会在编辑器中获得一个名为 OnValidate() 的回调,这是标记错误的好时机,而不是当您想将构建推出门时
-
我认为编译时间是我可以检查错误的最早时间,但我不知道 OnValidate() 回调,看起来它可能是我正在寻找的,谢谢!