- Home /
"Object reference not set to an instance of an object" This should work but it doesn't
var buildingTypes : GameObject[]; var buildIndex : int = 0; var notHere : boolean = true; var buildingHere : boolean = false;
function Update () { if(Input.GetMouseButton(0)){ //Check to see if there is a building checkForBuilding(); //If there isn't a building make one if(!buildingHere){ makeBuild(); //If there is a building destroy it }else{ destroyBuild(); } } }
//Check to see if there is a building function checkForBuilding() { var ray = Camera.main.ScreenPointToRay (Input.mousePosition); var hit : RaycastHit; if (hit.collider.gameObject.CompareTag("buildingTypes")){ //Tell unity there there is a building buildingHere = true; Debug.Log("One here"); } }
//Destroy Building function destroyBuild() { var ray = Camera.main.ScreenPointToRay (Input.mousePosition); var hit : RaycastHit; if (Physics.Raycast (ray, hit, 100) && hit.collider.gameObject.CompareTag("buildingTypes")){ Debug.DrawLine (ray.origin, hit.point); Destroy(hit.collider.gameObject); } }
//Make building function makeBuild(){ var ray = Camera.main.ScreenPointToRay (Input.mousePosition); var hit : RaycastHit; if (Physics.Raycast (ray, hit, 100) && hit.collider.gameObject.CompareTag("terrain")){ Debug.DrawLine (ray.origin, hit.point); Instantiate(buildingTypes[buildIndex],hit.point,Quaternion.identity); } }
Instead of the makeBuild(); function being run it throws up a debug log error "Object reference not set to an instance of an object" i can't see how I can reference an object that doesn't yet exists (although it is a prefab with the tag "buildingTypes")
Thanks - C
Answer by DaveA · Feb 04, 2011 at 05:50 PM
Assuming you have assigned some GameObjects in the Inspector to that array buldingTypes, check the buildIndex for out-of-bounds. If you have 3 elements, and the buildIndex is 3, it will fail like that (0,1,2 ok)
I'm still not completely with you, I've started by only assigning one GameObject in the hope this would be a simple process and allow me to in future add more GameObjects. Even with that the case and the buildIndex set to 1 (tried 0) I still get an error!
One object assigned, the index must only be 0. If that's the case, I'd hit the debugger and/or put lots of Debug.Log statements in to ensure that code is executing as planned.
Your answer
