4
votes
GameObject enemy = Instantiate(spawnObject,spawnPosition,spawnObject.transform.rotation) as GameObject;
enemy.transform.parent = transform;

The above code generates the expected result when I test my game in game mode, however I'm gettting this error message:

"Setting the parent of a transform which resides in a prefab is disabled to prevent data corruption."

Yes, the spawnObject variable contains a prefab, however creating a new GameObject should have fixed the problem, I assume?

2

2 Answers

2
votes

Check if your "transform" variable is actually from a gameobject and not from a prefab.

var transform = somePrefab.transform;
enemy.transform.parent = transform; // this won't work

var transform = someOtherGameObject.transform;
enemy.transform.parent = transform; // this will

Maybe you could give some more information about where that transform variable of yours comes from.

0
votes

I've been seeing this issue as well - an instantiated GameObject (not the prefab) giving this error message. My GameObject (A) had been parented into the middle of another instantiated GameObject (B) of a different type. I wanted to reparent A into another part of B - which would fail with the given error. My only solution has been to first reparent A to null, then reparent into B again.