An error occurs when trying to set a child to my GameObject in script

无人久伴 提交于 2020-06-27 10:45:00

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/14371903/an-error-occurs-when-trying-to-set-a-child-to-my-gameobject-in-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!