Object reference not set message, directly after instantiation
Hi Guys,
i have a LevelController script which is loading some data and then instantiates the Objects. As you can see, right after i instantiate my player Prefab, i tell my Camera about it, so my Camera is able to follow my player.
Problem is: The CameraController Scripts tells me, that there is no reference.
Setting Camera, player Gameobject and Camera ControllerScript in my LevelController which builds the Level (and so instantiates my player)
public Camera cami;
private CameraController cc;
private GameObject go_player;
cc = cami.GetComponent<CameraController>();
Later i do the instantiation and tell my Camera who the player is:
case 3:
go_player = Instantiate(Player_PreFab, position, Quaternion.identity) as GameObject;
cc.setTarget(go_player); // <----- I am telling my Camera about the player Gameobject
Then, in my CameraController i have the "setTarget" function i addressed above:
public void setTarget(GameObject go)
{
Debug.Log ("this function has been called");
target = go;
Debug.Log(go.transform.position);
}
Due to the Debug.Log i can see, that the function has been called, but right after that i receive this:
> NullReferenceException: Object
> reference not set to an instance of an
> object CameraController.setTarget
> (UnityEngine.GameObject go) (at
> Assets/Scripts/CameraController.cs:24)
> LevelController.GenerateTiles (Int32
> height, Int32 width) (at
> Assets/Scripts/LevelController.cs:56)
For me that sounds like: The instantiated GameObject player is not known by my cameraController. But, i gave the Gameobject player to the CameraController right after its instantiation.
Any help would be highly appreciated. KIM
Ok, what i found till yet: CameraController Scripts are fine, but getting some data from my player is also not working right after instantiation.
case 3:
go_player = Instantiate(Player_Prefab, position, Quaternion.identity) as GameObject;
Debug.Log (go_player.transform.position); //<-- throws exception
cc.setTarget(go_player);
break;
As i can see the player object flying around, i wonder how this can happen. $$anonymous$$aybe i am calling the player game objects too fast after instantiation?
Answer by KIMSCHMITZ · Nov 15, 2015 at 04:55 PM
And here is the answer to my problem.
I assigned Player_Pref via Drag& Drop in the inspector. Later i decided to change Player_Prefab to be a GameObejct (it was Transform before). I did so in my Script.
Of course(?) the assignment in the inspector got lost, but i did not look after this. Again a stupid thing - but this is how to learn :-) I reassigned the prefab and everything is working fine now.
I also learned that i do like more the programmatic assignment :-).
(And thanks to a colleague in my working place who showed me the way) Kind regards, KIMSCHMITZ