- Home /
Instantiate a prefab and parenting it?
Hello there, I'm having trouble with instantiating a prefab and making it a child of the object that it hits. This is the error that Unity gives to me :
"Setting the parent of a transform which resides in a prefab is disabled to prevent data corruption. UnityEngine.Transform:set_parent(Transform) Bullet:Update() (at Assets/Script/Bullet.js:39)"
and this is part of the script "interested" :
var HitHole : GameObject;
var power : int;
var HitParticleSpacing : float = 0.01;
function Update ()
{
var fwd = transform.TransformDirection(Vector3.forward);
var Hit : RaycastHit;
if (HitHole)
{
Instantiate(HitHole, Hit.point + (Hit.normal * HitParticleSpacing), Quaternion.LookRotation(Hit.normal));
HitHole.transform.parent = transform;
if (Hit.rigidbody !=null)
Hit.rigidbody.AddForceAtPosition(fwd * power, Hit.point);
}
}
I've someone can help me , I just don't know what's my error!
HitHole.transform.parent = transform; is the error, you don't need to parent bullets to the gameObject
Answer by aldonaletto · Nov 03, 2013 at 09:30 PM
You're trying to modify the prefab HitHole! Assign the result of Instantiate to a temporary variable and use it to modify the instance created, not the prefab:
...
if (HitHole){
// get a reference to the newly created object:
var hole = Instantiate(HitHole, Hit.point + (Hit.normal * HitParticleSpacing), Quaternion.LookRotation(Hit.normal));
// "glue" hole to the object hit:
hole.transform.parent = Hit.transform;
if (Hit.rigidbody !=null)
Hit.rigidbody.AddForceAtPosition(fwd * power, Hit.point);
}
}
...
If I do like that , for some strange reason, the prefab isn't instantiated at all! Any idea? :/
There was an error in your original code: the hole must be childed to the object hit in order to "glue" it to the target (line 6 in my answer). I have not noticed that at first, but now my answer is fixed.