- Home /
Trying to parent object to another object via script. "Setting the parent of a transform which resides in a prefab is disabled to prevent data corruption."
So I have a player object that instantiates a particle system that creates a muzzle flare. Everything is fine except I want the flare to be parented to the player. When I try this:
public class Flare : MonoBehaviour {
public GameObject Player;
// Use this for initialization
void Start () {
transform.parent = Player.transform;
}
I get this error:
Setting the parent of a transform which resides in a prefab is disabled to prevent data corruption.
I tried looking up the issue but I don't really understand the solutions that I came across. Can anyone explain a way to do this? Thanks.
You need an instance of your prefab to be able to set the parent. Right now, the prefab is not in your scene and therefore has no "parent". You need to "instantiate" (put it in the scene), in order to set the parent
You need to do the parenting in the instantiated object, not the prefab. So your code will be something like:
GameObject go = Instantiate(Player, somePosition, someRotation) as GameObject;
transform.parent = go.transform;
It worked perfectly, but only for one try. It was really odd, I just tested it, and it would instantiate and work properly, and then I ran the game again and now it won't instantiate. Everything is linked properly, I don't get any errors. This is the code:
EDIT: Never$$anonymous$$d, ignore my stupidity. It works, I accidentally turned off the emitter on the particle system! haha. Thank you Benproductions and robertbu.
You put your comment in an answer so it seems I can't mark yours as the correct answer, oh well. I'll just select the other one. Thanks though.
I didn't put my comment in as an answer because @D8ms was saying the same thing. I was just providing an example so that you would understand how to apply what he was saying.
Answer by D8ms · Jul 29, 2013 at 04:44 AM
Sounds like you are trying to change the parent of a prefab. Check to see that Player
refers to an object that's located in your scene, not the a prefab.
It is a prefab. I have it so when the shoot key is pressed, it instantiates a prefab of a muzzle flash particle system (which I want to parent to the player).
But to set the parent, it CANT be a prefab. I suggest looking at the examples in the documentation
Okay, I think I just thought of another way I could do the effect.
Edit: Nope, still trying to figure this out. $$anonymous$$y player is a prefab and I can't figure out any way to parent something to it this way.
try use GameObject.Find("GA$$anonymous$$EOBJECT INSTANTIATED").transform.parent = transform;