How to only Instantiate child of prefab?

I have a prefab parent with a prefab child inside.
I’m trying to duplicate the child prefab only.

parent prefab → child prefab, child prefab, etc
What I get instead is several pairs of “parent prefab → child prefab”.

I noticed that if I manually pull a child prefab to the scene, the parent also appears.

Is this impossible to do?
Here’s the code I’m using to instantiate.

Object prefabRoot = PrefabUtility.GetPrefabParent(originSprite);
GameObject newTiledSprite = (GameObject)PrefabUtility.InstantiatePrefab(prefabRoot);

originSprite is a reference to a gameobject.
I also tried using GetPrefabObject but I get “NullReferenceException: Object reference not set to an instance of an object”

Try this one. :slight_smile:

[SerializeField]
GameObject _prefabToInstantiate;

void Start ()
{
GameObject gObj = Instantiate(_prefabToInstantiate, transform.position, Quaternion.identity) as GameObject;
Destroy(gObj.transform.parent);
}

Here, I instantiated the Child Object of the prefab and then it gets the parent object to destroy. Is this what want to do?

NuDraconis’s code should work with one minor fix. Destroying the parent with gObj still as its child will destroy gObj (the desired child prefab) as well, so you first have to remove gObj’s parent before destroying it.

void Start () 
{
    GameObject gObj = Instantiate(_prefabToInstantiate, transform.position, Quaternion.identity) as GameObject;
    GameObject parentObj = gObj.parent;
    gObj.parent = null;
    Destroy(parentObj);
}
1 Like

Thank you both :slight_smile:
That worked perfectly.