- Home /
How to load nested prefab?
I have a Prefab. ParentPrefab, which contains child1, child2 etc.
I want to access child1 from my C# scripts.
I am able load ParentPrefab using Resource.Load("ParentPrefab"). But I dont know how to access ParentPrefab.child1 in some GameObject variable in C# script.
So you have nested prefabs, but only want to load the childPrefab?
Have you tried loading the childPrefab directly Resource.Load("childPrefab") ? (I guess you already tried that)
$$anonymous$$y guess is you'll have to load the parent prefab and then access the child with loadedParentPrefab.GetChild(#)
Answer by dorpeleg · Aug 13, 2013 at 07:28 AM
You need to do something like this:
GameObject parentObject = Resources.Load("ParentPrefab");
Then, you can use one of the following ways to get the child:
GameObject childObject = parentObject.transform.Find("child name");
GameObject childObject = parentObject.transform.GetChild(child index);
I don't think it's possible to load only the child from the resources.
Hey, for below syntax
GameObject childObject = parentObject.transform.Find("child name");
I see following error:
error CS0030: Cannot convert type
UnityEngine.Transform' to
UnityEngine.GameObject'
error CS0030: Cannot convert typeGameObject childObject = parentObject.transform.Find("child name");
UnityEngine.Transform' to
UnityEngine.GameObject'
the result of a Find is a Transform, not a GameObject, so you should either get the gameObject of the result of your find
GameObject childObject = parentObject.transform.Find("child name").gameObject;
or change the variable to a Transform class variable
Transform childTransform = parentObject.transform.Find("child name");
Thanks. That worked.
Can you also point me to nice coding tutorial for Unity?
Okay, great, accept dhawalbanker's answer then ;) So this question can be closed and added to the knowledge base.
And there are many tutorials out there, it all depends what you want to do. Look around on answers and on the forum, do a google search ^^
You'll find some Unity(not necessarily code-oriented) tutorials here
Your answer
Follow this Question
Related Questions
Import a prefab from file at runtime? 1 Answer
How to save a prefab when a button is pressed 1 Answer
load objects just if they in range of camera 0 Answers
How do I find a Prefab after I Replaced said Prefab? 1 Answer
Visualization of saved games inside a Load Menu - Problem with instantiated prefabs 0 Answers