0

在 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);
    }
}

4

1 回答 1

0

您得到的IndexOutOfBoundsException不是因为 Unity 没有找到孩子,而是因为您尝试访问/设置

wColliders[i]

一个列表。尚未添加任何项目,因此您无法通过索引访问它们。


你宁愿使用List<T>.Add

for(var i = 0; i < 4; i++)
{
    wColliders.Add(transform.GetChild(i).GetComponent<WheelCollider>());
}

或者实际上更简单地使用GetComponentsInChildren

wColliders = GetComponentsInChildren<WheelCollider>(true).ToList();
于 2021-01-30T22:04:32.547 回答