- Home /
Create variables dynamically
Hi,
I'm making a fps, where enemies comes in waves. I have a variable stating the total number of waves:
public int numberOfWaves
, so i can set this from the Unity UI.
Currently it's the same enemy model that spawns at each wave, and i would like to be able to a specific model for each wave. So something like this:
public GameObject enemyWave1;
public GameObject enemyWave2;
public GameObject enemyWave3;
These can however change, if i set numberOfWaves to 5. Is it possible to make those dynamic, so if i update numberOfWave, the amount of public GameObject enemyWave# will also change? :)
Hope you understand what i mean.
Thanks Morten
Answer by nasa8 · Feb 17, 2014 at 10:30 AM
Use Lists or Arrays instead os separate variables.
example with list:
using UnityEngine;
using System.Collections;
using System.Collections.Generic; //this is necessary for using lists
public class PlayerController : MonoBehaviour {
public List<GameObject> waves = new List<GameObject>();
public AddWave(GameObject go)
{
vawes.Add(go);
}
public DoSomethingWithAllWaves()
{
foreach (GameObject go in waves)
{
//here you can operate with go which will be processes for each wave
}
}
}
So in that case, i can drag the models/prefabs into "waves" in the unity interface? And they will be added to the list?
yes, you can. There a size of the List will be shown which you should set first. functions AddWave and DoSomething.... are given just as an example, there is no necessity to write them for using list.
Sounds like exactly what i need then :) Will try it when i get home, in a few hours. So far, thanks alot nasa8!
Your answer
Follow this Question
Related Questions
Accessing Dynamically Named Variables (javascript) 2 Answers
Dynamically call variables 2 Answers
How I do something like eval() but not eval() ? 1 Answer
UNet Dedicated Server 0 Answers
How to custom filter target objects? 0 Answers