- Home /
Fetching Prefabs and putting them in a list?
I'm attempting to generate a list of corporations, each one with randomized values. So far, this is working, but I can't help but think something in here could be done a lot better. Specifically, the code to fetch the Corporation prefab takes three lines, and requires the corporation to be in a "resources" folder instead of just in the asset folder.
Is there a simpler way to fetch an object? Is this janky fix how it actually works?
void generate()
{
int corpsToMake = 10;//# of corps to make
corpSet = new Corporation[corpsToMake];
shares = new int[corpsToMake];
for(int i = 0; i < corpsToMake; i++)
{
GameObject tempCorp = (GameObject) Instantiate(Resources.Load("Corporation"));
corpListSize++;
Corporation corp = (Corporation) tempCorp.GetComponent("Corporation");
corpSet[i] = corp;
Corporation cs = (Corporation) corpSet[i].GetComponent<Corporation>();
cs.setName(nameGen());
//cs.setName(Random.Range(1,100).ToString());
cs.setShares(Random.Range(50,100));
cs.setID(i+1);
}
// GameObject player = (GameObject) Instantiate(Resources.Load("Corporation"));
// playerCorp = (Corporation) player.GetComponent("Corporation");
// playerCorp.setID(100);
// playerCorp.setName("LevelZero");
// playerCorp.setShares(10000);
// playerCorp.player = true;
afterGen();
}
Answer by Statement · Mar 26, 2012 at 11:06 PM
Well, what are you trying to do? If you just need a link to the prefab, make a public variable and instantiate it. If you do that you end up with 1 line of code to create the copy.
corpSet[i] = (Corporation)Instantiate(corporationPrefab);
You could also come up with a factory method to create a random corporation, something like
public static Corporation Corporation.RandomCorp() { ... }
Your answer
Follow this Question
Related Questions
assign different values to prefabs on instantiation 2 Answers
setting the text of an instantiated prefab's child's guitext object 1 Answer
Get unity to recognize prefab in C# 2 Answers
Instantiated object rotation abruptly. 0 Answers
Instantiate prefab (button, texture) with attached script 1 Answer