在 Unity 中,我的玩家游戏对象有 4 个轮子,它们都包含轮子对撞机。我想得到这些的rpm。
我编写了这段代码,但在第 33 行它抛出了索引/参数超出范围异常,这意味着它试图使用“GetChild(i)”访问的索引不可访问。第 33 行是
wColliders[i] = gameObject.transform.GetChild(i).gameObject.GetComponent<WheelCollider>();
我的玩家有 5 个子对象,其中 4 个有轮子对撞机。如何解决?
```
public class PlayerController : MonoBehaviour
{
//[SerializeField] private float speed = 10f;
[SerializeField] private float speed;
[SerializeField] private float rpm;
private float totalRpm;
[SerializeField] private float horsePower;
[SerializeField] private float turnSpeed;
public float horizontalInput;
public float forwardInput;
[SerializeField] private GameObject centerOfMass;
[SerializeField] TextMeshProUGUI speedometerText;
[SerializeField] TextMeshProUGUI rpmText;
List<WheelCollider> wColliders;
private Rigidbody playerRb;
// Start is called before the first frame update
void Start()
{
playerRb = GetComponent<Rigidbody>();
playerRb.centerOfMass = centerOfMass.transform.position;
wColliders = new List<WheelCollider>();
for(int i = 0; i < 4; i++)
{
wColliders[i] = gameObject.transform.GetChild(i).gameObject.GetComponent<WheelCollider>();
}
}
// Update is called once per frame
void FixedUpdate()
{
horizontalInput = Input.GetAxis("Horizontal");
forwardInput = Input.GetAxis("Vertical");
playerRb.AddRelativeForce(Vector3.forward * horsePower * forwardInput);
transform.Rotate(Vector3.up, Time.deltaTime * turnSpeed * horizontalInput);
speed = playerRb.velocity.magnitude;
speed = Mathf.RoundToInt(speed);
speedometerText.SetText("Speed: " + speed);
for(int i = 0; i < wColliders.Count; i++)
{
totalRpm += wColliders[i].rpm;
}
rpm = Mathf.Round(totalRpm / wColliders.Count);
rpmText.SetText("RPM: " + rpm);
}
}