How to AddForce to a Rigidbody from Game Objects Spawned from an Array, One Prefab at a Time?


As the question say, I need to add force to a prefabs that are spawned from an array, and they need to be added to the prefab one at a time.

Let’s say there’s an array of 10 prefabs that are spawned and moving around. The next time the user clicks on the mouse, AddForce should be added to element 0 in the array, then the next time the mouse button is clicked AddForce should be added to element 1 in the array, so on and so forth. This should go all they way through until the end of the array.

What’s a good way to go about doing this?

I initially thought that just adding a public bool and flipping that when the mouse button is clicked, but of course this makes it so all elements in the array are affected by the AddForce.

How can I do it so only one prefab is affected on at a time?



I think you’ve got your terminology a bit confused. A prefab is a file in unity that acts as a ‘template’ for an object you can spawn in the world. I think what you’re saying is:

  • I have spawned 10 game objects (presumably by instantiating them from prefabs), and stored references to them in an array
  • When the mouse button is first clicked, I want to apply a force to object 0 in the array
  • When it is clicked again, I want to apply a force to object 1
  • etc etc

I suspect what you’re after is something along these lines:

GameObject[] spawned_objects;
int next_object_idx;

void Start()
	//presumably you spawn objects here using Instantiate and store them in the spawned_objects array?

	next_object_idx = 0;

void Update()
		//apply a force

		//move onto the next object

		//if we've gone past the end of the array, wrap it back around to 0
		if(next_object_idx > spawned_objects.Length)
			next_object_idx = 0;

Very simply:

int index = 0;
	GameObject[] objects = new GameObject[10] {ob1, ob2....obj10};
	public void MouseClicked()

		if (index >= 10)
			index = 0;

		objects [index].GetComponent<Rigidbody> ().AddForce (Vector3.up);

So use indexer and increment it when mouse is cliked.