- Home /
Prefabs wont instantiate?
So I have a for loop that triggers when an enemy dies and rolls a dice to see if it drops certain items. The for loop works fine, but 'lootBag' will not instantiate in the scene. There is no errors, and the console can return both the object itself and its value as well as position and none of it is null. What was also strange is when it said that it had spawned but wasn't in the scene, I checked its transform position, and it was exactly where another version of the prefab existed in the scene, so I thought maybe it was somehow getting refrence from that prefab in the scene or something. But, I deleted the prefab from the scene and the for loop returns its old postion. This probably has nothing to do with it, but I thought it might be relevant. I am very confused, and was wondering if anyone has any ideas?
Code:
public Item[] drops;
public float[] chance;
private float dice;
private GameObject lootBag;
public void dropLoot()
{
for (int i = 0; i < drops.Length; i++)
{
if (drops[i] != null) //checks if the item in the array is actually there.
{
if(chance[i] != 0) //checks if the drop chance is > 0.
{
dice = Random.Range(0, 100); //rolls dice for drop.
if (dice <= chance[i]) //checks if it landed in the chance range.
{
lootBag = Resources.Load<GameObject>("drops/DroppedItem");
Instantiate(lootBag, transform);
}
} else
{
Debug.Log(drops[i].name + "'s drop chance is zero. Why did you do that?"); //prints if the items chance is zero.
}
}
}
}
}
tried passing the reference directly and comment the lootBag = Resources.Load("drops/DroppedItem"); ?
Answer by mlnczk · Dec 10, 2018 at 08:00 AM
Try doing: Instantiate(lootBag, transform.position, transform.rotation); And if it doesnt work then add public GameObject lootBag and pass it in inspector for test purposes
Answer by DoubleSystem2 · Dec 10, 2018 at 06:50 AM
what object is this script on? i think it's on the enemy and if so, the way you are doing "Instantiate(lootBag, transform);" you are telling it to instantiate a lootbag as a child of the enemy, and that instantly destroys it if you are destroying enemies who die. Basically, you should do "Instantiate(lootBag, transform.position);" so that it spawns a lootbag at the position of the enemy who died, not as a child of it.
Your answer
Follow this Question
Related Questions
Instantiating a prefab as a child of an instantiated prefab 0 Answers
Changes to prefab instance generated from script aren't remembered 1 Answer
Using Part of prefab as script parameter 1 Answer
Setting parent of instantiated object fails (Error: setting parent of prefab is disabled...) 1 Answer
Accessing a prefab after instantiating results as null 1 Answer