0

I am facing this problem in Unity again and again. I cannot find solution. I think my code is right, but where is the problem?

GameObject visual = Instantiate<GameObject>(placementObject[num], hit.point + visualOffset, Quaternion.identity); 
visual.transform.SetParent(parentObject.transform); <--- Causing error

Any suggestions? Thank you for any feedback!

Dan Rais
  • 159
  • 2
  • 10
  • Why not use the option to specify parent at instantiation? – BugFinder Nov 23 '21 at 15:10
  • I can't reproduce this problem using the information in the question. Please include steps on how to produce the problem starting from a blank project including how to assign prefabs to `placementObject`, how to create those prefabs, etc. See [mre] for more details. – Ruzihm Nov 23 '21 at 15:24

2 Answers2

2

you could set the parent directly:

GameObject visual = Instantiate<GameObject>(placementObject[num], hit.point + visualOffset, Quaternion.identity, parentObject.transform); 

but using SetParent after Instantiate() should work, too. Check whether parentObject is not null.

rbcode
  • 327
  • 2
  • 7
  • Error: Cannot instantiate objects with a parent which is persistent. New object will be created without a parent. UnityEngine.Object:Instantiate(GameObject, Vector3, Quaternion, Transform) ObjectPlacement:Placing() (at Assets/ObjectPlacement.cs:80) ObjectPlacement:Update() (at Assets/ObjectPlacement.cs:60) At line 60 and 80 is the same row ->Visual.transform.SetParent(parentObject.transform); – Dan Rais Nov 23 '21 at 15:41
  • Thanks! The problem was that, i was using a prefab linked in different script and i do not noticed! Thank you! – Dan Rais Nov 23 '21 at 17:36
2

You are trying to assign a parent that is a prefab and not an instance of an object in your scene.

Ensure that parentObject is an actual object and not a prefab (or, if you're editing a prefab, ensure that it is an actual object within that prefab, and not an unreferenced prefab itself).

Chris
  • 444
  • 2
  • 12