For - loop question

Hello, I would like to automatically store 30 points in the array. I’ve tried writing a script, but it doesn’t work. Could you please suggest how to make it work properly?

Thank you!
using UnityEngine;
using System.Collections;

public class randompoint: MonoBehaviour {

	public Transform target1;
	public Transform target2;
	public Transform target3;
	public Transform target4;
	public Transform target5;
	public Transform target6;
	public Transform target7;
	public Transform target8;
	public Transform target9;
	public Transform target10;
	public Transform target11;
	public Transform target12;
	public Transform target13;
	public Transform target14;
	public Transform target15;
	public Transform target16;
	public Transform target17;
	public Transform target18;
	public Transform target19;
	public Transform target20;
	public Transform target21;
	public Transform target22;
	public Transform target23;
	public Transform target24;
	public Transform target25;
	public Transform target26;
	public Transform target27;
	public Transform target28;
	public Transform target29;
	public Transform target30;

	//create array from points
	public Transform[] allpoints;

	
	// Use this for initialization
	void Start () {

		allpoints = new Transform[30];
		
		for(int i = 0; i < 30; i++){
		allpoints *= "target" + i.ToString();*

_ Debug.Log(allpoints*);_
_
}*_

* }*
}

Hi, you can just drag them in the inspector to an array if you have them in scene.

I’m afraid you can’t just access a variable by crafting it’s name as a string. In this case you’re going to have to add each variable manually:

allpoints[0] = target1;
allpoints[1] = target2;
...
allpoints[29] = target30;

Alternatively, you could also assign the targets directly to the array through the editor.

If you have placed the targets in the scene or they are being instantiated through a script, you could also use this:

//Assumes all target gameobjects are tagged "Target"
allpoints = GameObject.FindGameObjectsWithTag("Target");

You are trying to put strings in an array expecting Transforms so it won’t work.

This being said, there is absolutely no need to declare all your “targets” only to put them in an array. Instead your code should be:

 public class randompoint: MonoBehaviour {
 
     //create array from points
     public Transform[] allpoints;
     
     // Use this for initialization
     void Start () {
     }
 
 }

This way you can drag and drop transforms in your “allpoints” variable in the editor (the size of the array will be adjusted automaticaly).