How to instantiate a prefab using a string variable ?
I like compact code, and have had to resort to this abomination (below) because I just could not figure out how to reference a prefab name via a dynamically created string.
if(winningsAmount >= 1000)
{
instance = Instantiate(chip1000, chipStartPosition, Quaternion.identity );
}
else if(winningsAmount >= 500)
{
instance = Instantiate(chip500, chipStartPosition, Quaternion.identity );
}
else if(winningsAmount >= 100)
{
instance = Instantiate(chip100, chipStartPosition, Quaternion.identity );
}
else if(winningsAmount >= 25)
{
instance = Instantiate(chip25, chipStartPosition, Quaternion.identity );
}
else if(winningsAmount >= 5)
{
instance = Instantiate(chip5, chipStartPosition, Quaternion.identity );
}
else{
instance = Instantiate(chip1, chipStartPosition, Quaternion.identity );
}
I would much rather to something like this, but I get errors and everything I have researched and try just won't work.
string value = 1000;
prefabName = "chip"+value;
instance = Instantiate(prefabName , chipStartPosition, Quaternion.identity );
Answer by Gutthegut · May 04, 2017 at 05:03 PM
That's beacause you are trying to instantiate the prefab by his name while you should call the GameObject.
You should have something like
GameObject myPrefab = GetComponent<prefabName>;
[...]
instance = Instantiate(myPrefab, chipStartPosition, Quaternion.identity);
You can also do it with:
public GameObject[] chip;
int value = 1000
[...]
instance = Instantiate(chip[value], chipStartPosition, Quaternion.identity);
Hope this will help you. =)
Thanks, but your first suggestion just doesn't work.
The second might be viable in theory but will require that each prefab has an ID. Otherwise I would need an array 1000 long in order to be able to store "chip1000" in index 1000. Not practical at all to do via the inspector, but maybe I can assign them into an array at runtime. Still not ideal though...
Surely there is a way to dynamically create a GameObject's name and then be able to reference it?
Okay, my bad i didn't understand the question properly.
if i did undestand you want to create instance of an object and then reference it.
try something like
GameObject[] instance;
instance[value] = instantiate(prefab, position, rotation);
Anyway you can't create a dynamic var name with C# you'll ave to use list or array.
I want to assign a string and be able to instantiate the prefab which matches that string.
Anyway you can't create a dynamic var name with C# you'll ave to use list or array.
But that seems to answer my question right there.