- Home /
How to Spawn Object at next Empty Location
I have a very simple script that spawns an item when the player mouse clicks a button. Now I want to have multiple items that spawn in the next empty slot (basically like an inventory system, if one slot is full it automatically uses the next slot)
public class spawnItem : MonoBehaviour
{
public GameObject newItem;
public Transform slotOne;
void OnMouseDown()
{
Instantiate(newItem, slotOne.position, slotOne.rotation);
}
}
I now have 3 empty slots(spawn points) how do I get it to recognise that the first one is full and add the item to next slot? I'm guessing I need to use a bool, starting at false, then true one the object has been instantiated. Am I going to need a script on each of the slot transforms to tell this script they are either empty or full?
Any help greatly appreciated.
Ins$$anonymous$$d of an unnecessary bool, if the slot is not null, it's full, right?
Depending on your system you could have an index that moves forward whenever a slot gets filled, if the whole thing is consecutive.
If not, two lists, one with available, one with filled slots could be a solution, where you live slots around.
Answer by Tony_T · Sep 25, 2017 at 04:19 PM
Your thinking is correct if you want it to be like an inventory because you may want to check if a slot is empty more than once. You can use bools like you said yourself to check if the slot is emtpy.
First you need to use this variable type since you have multiple spawn points:
public Transform[] Slots;
Then to check if a slot is empty you can use bools for every slot like this:
public bool Slot1; //false = empty, true = not empty
If (Slot1 == false)
{
Instantiate(newItem, Slots[0].position, Slots[0].rotation);
}
else if (Slot1 == true)
{
//do nothing
}
Sorry for delayed response. Yep that worked. Thanks