- Home /
Howto set main.camera as a parent when main.camera itself is a child of a prefab
So with below code, I am trying to make an instantiated object the child of main.camera so it looks as if the person activating it is "holding it"
using UnityEngine;
using System.Collections;
public class Haxxor3000Behaviour : MonoBehaviour {
private GameObject haxxorObject;
private Transform cameraTransform;
void SwitchState (bool setActive) {
cameraTransform = Camera.main.transform;
if(setActive){
haxxorObject = Instantiate(this, cameraTransform.position + cameraTransform.forward * 2, cameraTransform.rotation) as GameObject;
this.transform.parent = cameraTransform;
} else{
Destroy(this);
}
}
// Update is called once per frame
void Update () {
}
}
However this results in the following error:
Setting the parent of a transform which resides in a prefab is disabled to prevent data corruption.
I think this happens because main.camera is itself a child of the prefab player.
Is there any way to fix this? or maybe another solution to this problem I am not seeing?
All help is appreciated,
cheers Nopogo
Answer by Wolfram · Feb 02, 2013 at 05:05 PM
Assuming this script is part of your prefab, don't you mean
haxxorObject.transform.parent = cameraTransform;
?
I tried that also. But weirdly haxxorObject is null so that results in a NullReferenceException
which I should have mentioned since that also baffles me.
edit
After looking around some more I changed the instantiation to:
private Transform haxxorTrans;
haxxorTrans = (Transform) Object.Instantiate(this, cameraTransform.position + cameraTransform.forward * 2, cameraTransform.rotation);
But this resulted in a:
InvalidCastException: Cannot cast from source type to destination type.
I feel that takes me 1 step further towards the solution, but now I'm stuck again :P
Ah, I see. "this" is your script object, which is a monobehaviour. If you use "gameObject" ins$$anonymous$$d, Instantiate can be casted to GameObject. Or with your latest version, replace "this" with "transform".
Instantiate will always clone the whole GameObject (-hierarchy), no matter which subcomponent of the parent you feed to it. However, the object returned will be of the same type as the object you put in.