Create new variable name based on array index

Hello friends,

I am currently storing a bunch of Vector3 positions in an array. When a user clicks the screen, I am using a Raycast to get the location, sticking it in the array, and then instantiating an object at that location.

I would like to access the properties of those instantiations (ie. their rotations) for other game related calculations. However, my function currently does not create a new variable for each instantiation, so I can’t access the GameObjects.

I was thinking something like this would make sense in my function:

var gameObject[positions.Count] = Instantiate(marker, .., ..);

(actually using a List, hack because of Vector3 array complications). This would hopefully result in something like “gameObject1”, “gameObject2”, etc. How could I append the index number (or count in this case) to the variable name?

Thanks

Did you initialize the array of GameObjects? Is it an array?

If it is an constant size array, you should do:

var gameObjects : GameObject[Max_Number_Of_GameObjects];

If it is not constant, you need to use Array or List for the game objects too.

var gameObjects = List.<GameObject>();

And then Add GameObject as you instantiate them

Generally, you should make sure a value you initialize (in this case - a GameObject you instantiate), did so successfully.
I’d do something like this:

// Initialize memory
var gameObjects : Array = new Array();
var newGameObject : GameObject = Instantiate(marker, .., ..) as GameObject;
if ( !newGameObject )
   Debug.LogError("Could not initialize a newGameObject!");
else // Now you know a GameObject was actually created
{
   // Add the GameObject to the array
   gameObjects.Add(newGameObject);
   // Output the position of the last GameObject added (Coount - 1)
   Debug.Log("Position of GameObject: " + (gameObjects[gameObjects.Count-1] as GameObject).transform.position);
}

Have you got an “else” there?
Don’t insert the reference if it is null - that’s why I put an else before doing the “Add” to the array.

Do you know coroutines?
You can have all this code inside a coroutine and wait a frame before checking for the object initialization.

For instance:

function CallingFunction()
{
  StartCoroutine("AddMarker");
}

function AddMarker()
{
   var tempObj : GameObject = Instantiate(marker, selected.point, transform.rotation) as GameObject;

   yield;

   if(!tempObj)
   {
      print("failed to instantiate tempobj");
   }
   else
   {
     gameObjects.Add(tempObj); 
     print(gameObjects.Count);
   }
}