Search code examples
c#unity-game-enginetransformgameobjectprefab

Setting a prefab as child of another game object in unity


 public GameObject aiArrow;
 aiArrow.transform.parent = this.gameObject.transform;

When I try to set up a prefab as a child of another object the following error occurs.

Setting the parent of a transform which resides in a Prefab Asset is disabled to prevent data corruption

How to Set up this "aiArrow" Prefab as a child of another game object.


Solution

  • You can do this action right in the Instantiate() function call.

    public Transform parentObject;
    public GameObject prefab;
    
    public void CreateObject()
    {
       Instantiate(prefab, parentObject);
    }
    

    The method Instantiate has several overloads, where you can specify a parent object. This was the simplest example. Important! The example above does NOT modify position or rotation. It only acts as you would drag&drop a gameobject in the Hierarchy below another one. See Instatiate for the overload you need.