Change rigidbody values on mutliple objects (ARRAY)

Hello! I’m working on a game where I need to change the values of multiple objects with the same tag.

The idea is that the rigidbody only moves while the player does.

I have code that works, but only for one object because, despite scouring the forums and documentation for hours, I don’t understand arrays.

Essentially the code:

  1. Finds the character controller
  2. Detects if it’s moving
  3. If so, finds the object tagged “rbTime” and lets it move.
  4. Else, finds the object tagged “rbTime” and stops it.

The issue is that I need this to work on ALL objects tagged “rbTime”, not just one.

Here’s my code - can someone help me make it work with all objects tagged and explain why it works?

#pragma strict

public var player : GameObject;



var isStopped : boolean = false;




function Start() {


	
}

function Update () {
	
	var controller : CharacterController = player.GetComponent(CharacterController);
	if(controller.velocity.magnitude < 1) {
	
	physStop();
	
		
	} else {
	
	physStart();
	
	
	}

}

function physStop() {

	
	var b : GameObject = GameObject.FindGameObjectWithTag ("rbTime");

	var rb = b.GetComponent(Rigidbody);
	
	if (isStopped == false) {
	
	
	rb.velocity = Vector3.zero;
	rb.useGravity = false;
	rb.isKinematic = true;
	
	isStopped = true;
	
	}
	

}

function physStart() {

	var b : GameObject = GameObject.FindGameObjectWithTag ("rbTime");

	var rb = b.GetComponent(Rigidbody);

	if (isStopped == true) {
	rb.isKinematic = false;
	rb.useGravity = true;
	
	isStopped = false;
	}
	

}

Thanks!

-Sam

  • Use FindGameObjectsWithTag instead of “Object”
  • put them in a list or array
  • apply the method for each item in the array using a loop