- Home /
Switch Case List of Game objects ??
I know its not possible to use a list or array to switch case ,so Im wondering how can I possibly switch case a list of game objects ? there's a function that assigns the the gameObject "primaryWeapon" from the list of game objects ...so basically its obtains its reference from the Weapons list ....
public List<GameObject> Weapons = new List<GameObject>();
public List<GameObject> WeaponDropPrefab = new List<GameObject>();
public GameObject PrimaryWeapon;
switch (PrimaryWeapon){
case "PotatoLauncher":
WeaponDrop = WeaponDropPrefab.Find(w => string.Equals(w.name,"PotatoLauncher"));
Instantiate(WeaponDrop,transform.position,transform.rotation);
PrimaryWeapon=null;
break;
case "SlingShot":
WeaponDrop = WeaponDropPrefab.Find(w => string.Equals(w.name,"SlingShot"));
Instantiate(WeaponDrop,transform.position,transform.rotation);
PrimaryWeapon=null;
break;
case "Sphere1":
WeaponDrop = WeaponDropPrefab.Find(w => string.Equals(w.name,"Sphere1"));
Instantiate(WeaponDrop,transform.position,transform.rotation);
PrimaryWeapon=null;
break;
}
Answer by nixcs2512 · Jul 31, 2013 at 11:15 AM
Basically you only need set switch (PrimaryWeapon.name) because all your cases are set with string type.Or if you want to keep switch (PrimaryWeapon) you need to change your code a bit:
GameObject PotatoLauncher = WeaponDropPrefab.Find(w => string.Equals(w.name,"PotatoLauncher"));
GameObject SlingShot = WeaponDropPrefab.Find(w => string.Equals(w.name,"SlingShot"));
GameObject Sphere1 = WeaponDropPrefab.Find(w => string.Equals(w.name,"Sphere1"));
switch (PrimaryWeapon){
case PotatoLauncher:
Instantiate(PotatoLauncher,transform.position,transform.rotation);
PrimaryWeapon=null;
break;
case SlingShot:
Instantiate(SlingShot,transform.position,transform.rotation);
PrimaryWeapon=null;
break;
case Sphere1:
Instantiate(Sphere1,transform.position,transform.rotation);
PrimaryWeapon=null;
break;}
Answer by RandomiaGaming · May 17, 2019 at 06:59 PM
visual studio is complaining because it says a constant value is expected in the place of Any GameObject Variable.
switch(Any GameObject){
case Any GameObject Variable: Method(); break;
Your answer
![](https://koobas.hobune.stream/wayback/20220613111246im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to create an array of Transforms 1 Answer
How To Get A Reference To All Nearby GameObjects? 1 Answer
A node in a childnode? 1 Answer