2
 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.

Savad
  • 1,240
  • 3
  • 21
  • 50

1 Answers1

7

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.

B3NII
  • 375
  • 1
  • 10
  • I'm wondering if there's a way to instantiate under a parent, but insert it in between some existing child prefabs (not just at the end). Purpose is during a refresh/reload to reuse some of the child prefabs via SetActive(bool) rather than destroying them and re-instantiating everything. – KevinVictor Feb 23 '22 at 14:27
  • Oh, found this... https://stackoverflow.com/questions/36106736/unity-add-child-to-children-but-at-top – KevinVictor Feb 23 '22 at 14:31
  • And this... https://stackoverflow.com/questions/52651495/is-setasfirstsibling-or-setaslastsibling-better-to-use-in-unity – KevinVictor Feb 23 '22 at 14:45