- Home /
How to load instances of a prefab to an array c#
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;
             }    
         }    
     }
Thank you in advance
Answer by callen · Dec 10, 2015 at 02:55 PM
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[i] = 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;
 
              Debug.Log (balloons[index].gameObject.name);
              Vector2 moveDelta = Vector2.up*speed*(Time.deltaTime);
              balloons[index++].transform.Translate(moveDelta);
 
              index = index % balloons.Length;
          }    
      }
Answer by JedBeryll · Dec 10, 2015 at 02:24 PM
This should work if you set the gameobject tags correctly.
 balloons = GameObject.FindGameObjectsWithTag("myTag");
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                