- Home /
Other
Prefabs wont instantiate using a for loop?
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.
}
}
}
}
}
Answer by bburtson09 · Dec 05, 2018 at 05:32 AM
"If you have multiple Resources folders you cannot duplicate use of an asset name."
Resources.Load , Loads an asset stored at path in a folder called Resources. The path is relative to any folder named Resources inside the Assets folder of your project.
I'm going with the wild assumption that you may have more than one resources folder in assets and/or you probably created a couple test-runs of your prefab.
Just have a hunch you that you are loading a prefab you didn't expect.
hope i nailed it good luck
I looked and I dont have any other Resources folders... Also instantiating other prefabs hasn't had this issue so far, its just this one. What do you mean by 'test runs of my prefab'? do you mean a copy with the same name in the project folder or in the scene?