In Unity, my player gameObject has 4 wheels and all of them contain wheel colliders. I want to get the rpm of these.
I write this code, but at line 33 it is throwing index/argument out of bound exception, which means the index it's trying to access with 'GetChild(i)' is not accessible. line 33 is
wColliders[i] = gameObject.transform.GetChild(i).gameObject.GetComponent<WheelCollider>();
My player has 5 child objects and 4 of them have a wheel collider. how to solve it?
```
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);
}
}
You get the IndexOutOfBoundsException
not because Unity doesn't find the child but rather because you try to access/set
wColliders[i]
of an empty list. There are no items added yet so you can not access them via the index.
You would rather use List<T>.Add
for(var i = 0; i < 4; i++)
{
wColliders.Add(transform.GetChild(i).GetComponent<WheelCollider>());
}
Or actually rather simply use GetComponentsInChildren
wColliders = GetComponentsInChildren<WheelCollider>(true).ToList();