Hello! I am new to posting on Unity Answers, though I have been stalking the threads for answers to my problems for quite sometime now… ![]()
I am having an issue setting the transform of a game object that I have already instantiated. Now I’ve seen several threads already where people have similar issues, but they are all trying to change the transform of the prefab. I have instantiated the prefab into a variable and I am trying to change the transform of that variable. Here is the bit of code that I am talking about.
var single : GameObject;
private var temp:GameObject;
temp = GameObject.Instantiate(single, location, single.transform.rotation) as GameObject;
temp.transform.parent = transform;
The really frustrating part is that I’m doing this somewhere else in my code (what I believe to be the exact same thing) and it works. This one however…does not.
Also, the exact error I am getting:
“Setting the parent of a transform which resides in a prefab is disabled to prevent data corruption.
UnityEngine.Transform:set_parent(Transform)”
Thanks a lot for any help!
I think you're not supposed to overwrite transforms directly. Grab the position and rotation and set those: temp = GameObject.Instantiate(single, location, single.transform.rotation) as GameObject; temp.transform.parent.position = transform.position; temp.transform.parent.rotation = transform.rotation; I guess there is some extra issues setting the transform directly with prefabs as they all come from the same template object.
– HuacanachaWell, as I said above, I have code elsewhere that looks identical to this and it works, so I don't know why it wouldn't work here. I did however try your suggestion and now I'm getting a NullReferenceException. > NullReferenceException: Object reference not set to an instance of an object UnitManager.BuildUnit (System.Object unit, System.Object location) (at Assets/Scripts/Player Scripts/UnitManager.js:77) This makes me think that my instantiation is returning a null, but I've checked each of the parameters and 'single' is a game object and 'location' is a position.
– rheadedstepchyldHmm I didn't change the "temp =" line from your original code, is that where the error is thrown? If not is temp null after the call to Instantiate? And you said you checked that single, location and single.transform are all objects (not null)?
– HuacanachaI didn't change it either. Every time I have gotten an error, it has always been on the 'temp.transform...' line. Yeah, I just double checked. Single, location, and single.transform.rotation are not null.
– rheadedstepchyldAh of course the parent transform is null because it's not set to anything yet. Having read the transform.parent docs again it looks like what you are doing should work. Clearly it's some issue related to the prefab but I'm not sure what.
– Huacanacha