- Home /
Instantiate as child of a to-be-instantiated list item
Hey =)
I have a bit of trouble transfering what I read in the previously asked questions about this topic in this discussion board to my own problem and would appreciate a bit of help.
I have a few lines of code that look like this:
for (int i = 0 ; i < 3 ; i++)
{
kandidatenliste.Add (Instantiate(npcs.npc[i], KupplerinTransform));
heiratskandidaten.Add (Instantiate(heiratskandidatPrefab, XXX ));
heiratskandidaten[i].name = "Kandidat: " +npcs.npc[i].vorname +" "+ npcs.npc[i].nachname;
}
"XXX" describes where my thought process takes a break. I want to instantiate "heiratskandidaten" as a child of each entry of "kandidatenliste". Right now, it is being instantiated right underneath it.
I have found a couple questions which sounded the same, but I have not found a question where the to-be-instantiated object needs to be the child of a to-be-instantiated list item...
Help would be appreciated :)
Answer by BastianUrbach · Apr 14, 2018 at 08:57 PM
Shortest option (requires System.Linq):
heiratskandidaten.Add (Instantiate(heiratskandidatPrefab, kandidatenliste.Last() ));The same without Linq:
heiratskandidaten.Add (Instantiate(heiratskandidatPrefab, kandidatenliste[kandidatenliste.Count - 1] ));And a version that is more readable imo but a bit longer:
var kandidat = Instantiate(npcs.npc[i], KupplerinTransform); var heiratskandidat = Instantiate(heiratskandidatPrefab, kandidat ); kandidatenliste.Add (kandidat); heiratskandidaten.Add (heiratskandidat);
Thank you so much :D! I've tried your solutions, but none seemed to work - but they brought me to the right solution! I hadn't understood that a list entry could be its own Transform in my hirarchy =D Based on that, I added a temporary transform for the last entry in the list and now, it works like a charm :)!
kandidatenliste.Add(Instantiate(npcs.npc[i], $$anonymous$$upplerinTransform));
Transform tmpTransform = kandidatenliste[i].transform;
heiratskandidaten.Add (Instantiate (heiratskandidatPrefab, tmpTransform));
Now, I wonder why "kandidatenliste.Last()" and "kandidatenliste[kandidatenliste.Count - 1]" didn't work... But I will leave that particular head-scratcher to tomorrow.
Thanks a ton, you've helped me a lot =)!
Hm, do your lists contain GameObjects or Transforms? Only a transform can be set as parent so that might be the reason.
Your answer
Follow this Question
Related Questions
Instantiated Bullets Not Picking Up Correct Position/Rotation 2 Answers
[SOLVED] How can I check what was the last instantiated object? 2 Answers
How would I make this Cloned Function Copy to an endless amount? 1 Answer
Cloning Objects with Instantiate() - variables/references for added Components not stored? 3 Answers
Is Instantiating bullets/many objects always bad for performance? 1 Answer