- Home /
Unity not Instantiating Prefabs Properly
I'm creating a dungeon generator, where a corridor piece (as a prefab) is created, and then checks if there's anything in front of it before instantiating another piece.
However, the prefab created isn't always the prefab I have in my library, and I have no idea why. Shouldn't they always be equal?
Here is the prefab, expanded in my library:

And here is the view of my hierarchy, after the first piece is instantiated:

As you can see, the 'room_collider' piece is missing, why would this be?
Sure, here's the code for the first room generated.
 static var room_number = 15;
 static var closet_number = 3;
 static var elevator_number = 1;
 
 var prefab1 : GameObject;
 var prefab2 : GameObject;
 var prefab3 : GameObject;
 
 var prefabList = new Array ();
 
 var room_connect : Transform;
 
 //Create a room on the room_connect, selecting from the list
 function createRoom () {
 
     var prefabIndex = UnityEngine.Random.Range(0,prefabList.length - 1);
     Instantiate(prefabList[prefabIndex], room_connect.position, room_connect.rotation);
                 
     room_number = room_number - 1;
     Debug.Log("Room Created! Rooms Remaining: " + room_number);
     
 }
 
 function Start () {
 
     // Add prefab rooms to Array
     prefabList.push (prefab1);
     prefabList.push (prefab2);
     prefabList.push (prefab3);
 
     createRoom();
 }
The pieces of corridor were assigned to each prefab slot respectively.
You should use built-in arrays ins$$anonymous$$d of what you're doing.
eg : var prefabs : GameObject[] ; <--can be set in inspector drag/drop
Also, Random.Range(int, int) is exclusive of max. [(0,3) will return 0 || 1 || 2] So you use prefabs.length without the (-1), else your random number will never be the last index of the array [(0,3-1) will return 0 || 1].
Thanks the new code is a lot cleaner:
 //Set variables for room numbers needed
 static var room_number = 15;
 static var closet_number = 3;
 static var elevator_number = 1;
 
 //Array of possible rooms
 var prefabList : GameObject[];
 
 //Transform of the spawn point of the next room
 var room_connect : Transform;
 
 //Function to create a room on the room_connect, selecting from the list
 function createRoom () {
 
     //Create a random room from a random position on the list 
     var prefabIndex = UnityEngine.Random.Range(0,prefabList.length);
     Instantiate(prefabList[prefabIndex], room_connect.position, room_connect.rotation);
         
     //Decrease the number of rooms availiable
     room_number = room_number - 1;
     Debug.Log("Room Created! Rooms Remaining: " + room_number);
     
 }
 
 createRoom();
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                