- Home /
Why is it trying to grab the wrong rigidbody?
From my understanding, foreach loops through an array of objects; if no elements are present in that array it returns null.
Going off that information, I have a foreach loop that doesn't seem to be executing properly:
void MovementControl() // Controls platform movement
{
Vector3 movementVector = new Vector3(0f, 0f, moveSpeed * Time.deltaTime);
platformRigidbody.velocity = movementVector;
// Cycle through GameObject[] platforms and add a movement speed via force onto rigidbody
platforms = GameObject.FindGameObjectsWithTag("Platform");
foreach(GameObject platform in platforms)
{
platformRigidbody = platform.GetComponent<Rigidbody>();
platformRigidbody.velocity = movementVector;
if(platform.transform.position.z > removePositionZ){ Destroy(gameObject); }
}
}
The above code should cycle through every GameObject, find the attached rigidbody and apply a movement vector onto it.
So, why does it try to grab the rigidbody from the Spawner?
Answer by wfreeman480 · Jan 04 at 02:36 AM
Not 100% sure how foreach loops work but check out this thread here to see if it helps!
https://answers.unity.com/questions/164600/foreach-loop-with-an-array-of-gameobjects.html
Thanks for the reply! I was able to figure out the issue.
Just under the Vector3 instantiation there is platformRigidbody.velocity = movementVector; which also appears in the foreach loop. Removing this line fixed the issue.
Not entirely sure as to the reasoning for this but it was the solution. Hopefully someone with a little more experience will be able to shed some light.
Your answer
Follow this Question
Related Questions
Why my capsule collider sometimes stucks in other colliders? 0 Answers
Kinematic rigidbody movement. 2 Answers
Rigidbody slows down while turning using torque 1 Answer
Unity3D Pressure Plate request. 3 Answers
foreach Gameobject in array problems 1 Answer