Hello,
I’m trying to make instances of a prefab change their positions one at a time when a button is clicked.
my idea is to make an array of the prefab instances using find tag then use it in onClick function.
My code doesn’t work and I don’t know how to fix it. Please help
public GameObject[] balloons;
// ?? I don't know how to add the instances to the array
public void OnClick()
{ if (GameManager.instance.WrongButtonSelected == false && currentSelected == false)
{
GameManager.instance.WrongButtonSelected = true;
currentSelected = true;
for ( int i=0;i<balloons.Length;i++){
Debug.Log (gameObject.name);
transform.Translate(Vector2.up*speed*(Time.deltaTime));
break;
}
}
}
If you are creating these ‘instances of a prefab’ using Instantiate() in your code, you would likely be adding them to the array at the same time, like
for(int i=0;i<balloons.Length; i++)
balloons *= Instantiate(BalloonPrefab.gameObject) as GameObject;*
On the other hand, if these are instances you’re creating in the editor, you can drag-and-drop them into the array. Just take each of the GameObject instances from the Hierarchy panel, and drag into the public, editor-visible Balloons array, on whatever object has this script. Now, onto the matter of your logic, I also dont think that will give the results you desire. Your for-loop, since it uses a break statement, will only ever move the first (index-0) element. I think if you tried something like this, it would give you what you want “change their positions one at a time when a button is clicked” int index = 0;
public void OnClick() { if (GameManager.instance.WrongButtonSelected == false && currentSelected == false) { GameManager.instance.WrongButtonSelected = true; currentSelected = true;