Spawn Prefab based on int value
Hello! Iam trying to Spawn a Gameobject based on a UI selection in a previous Scene where you can select between 12 things (saved as int)
so i have this one int which is between 0 and 12 in a public int nav1Position; which persists between all scenes (DontDestroyOnLoad(this.gameObject);)
and as soon as i call this function:
public void SpawnStuff () {
Instantiate(prefab, new Vector3(0, 0, 0), Quaternion.identity);
}
the right prefab should spawn. which are defined is public GameObjects so like if int = 1 - spawn Towel.prefab if int = 2 - spawn Bucket.prefab ... and so on. how can i do this?
here is how it looks at the moment:
using UnityEngine;
using System.Collections;
public class Game : MonoBehaviour {
public int nav1Position;
public GameObject[] SpawnObjects = new GameObject[12];
void Awake() {
DontDestroyOnLoad(this.gameObject);
}
public void SpawnStuff () {
if (nav1Position = 1)
{
//how can I Spawn Object Number 1 here?
Instantiate(SpawnObjects, new Vector3(0, 0, 0), Quaternion.identity);
}
}
//ignore this line
public void LoadGameLevel (){
Application.LoadLevel("Race");
}
}
Answer by Garazbolg · Nov 09, 2015 at 11:05 AM
I assume you have all our prefab in SpawnObjects set in the inspector, so to select the item at nav1Position (wich i assume is your int to select the prefab) you can acces it like in any Array : with brakets
public void SpawnStuff () {
Instantiate(SpawnObjects[nav1Position], new Vector3(0, 0, 0), Quaternion.identity);
}
But you should also do so check to be sure that this GameObject is set in the inspector like this :
public void SpawnStuff () {
if( SpawnObjects != null &&
SpawnObjects.Length > nav1Position &&
SpawnObjects[nav1Position] != null
)
Instantiate(SpawnObjects[nav1Position], new Vector3(0, 0, 0), Quaternion.identity);
}
Hope that helps you.