Parenting problem

Hi guys I’m trying to instantiate an object with a parent to a point of view but i get null reference. Here is the code:

var showMessage : boolean;
var someMessage : String;
var prefab : Transform;
var pov : GameObject;

private var video : GameObject;

function OnGUI(){
    if(showMessage){
        GUI.Box(Rect(Screen.width/2,Screen.height/2, 100, 25),someMessage);
    }
}

function OnTriggerEnter(){
    showMessage = true;
    videostart();
}

function OnTriggerExit(){
    showMessage = false;
}

function videostart() {
    video = Instantiate(prefab, pov.position, pov.rotation) as GameObject;
    video.transform.parent = pov.transform;
}

Nop because the sphere (the testing prefab) is there when enter the trigger. The problem is that the sphere is not parented to the pov :( POV prefab with a sphere (if I drag the prefab in the scene it works)

–

1 Answer

1

When you get a null reference error, the error will be said to have happened at a particular source line. When posting these questions, always identify which source line in the script code Unity has detected the error upon. Also, have a practice with “code” formatting in the posts.

Assuming that the error occurs at the Instantiate line then either:

  1. prefab is null
  2. pov is null

Check, check and double check that these publicly exported variables have values.

I would say this is a valid answer ;) converted!

–

BTW: just realised that "pov" is a GameObject. A GameObject doesn't have a position or rotation property, only the Transform component. The best thing is to change the type of the pov variable to Transform and reassign the object to the variable.

–

Furthermore, please do not write parts of your code that are obviously not relevant. OnTriggerExit and the GUI, for instance.

–

Argh :D another thing: prefab is of type Transform and you try to as-cast it to GameObject. This will always fail since a GameObject and a Transform are two totally different things. The as-cast in it's nature will return null when the cast fails, so your "video" variable will always be null. Get your types right. You might want to use <a href="http://unity3d.com/support/documentation/ScriptReference/index.Performance_Optimization.html">pragma strict</a> to avoid such mistakes in the future.

–