The question is answered, right answer was accepted
NullReferenceException after build
I'm having problems after build. In preview everything works fine but after build there are errors. After build I'm having the exception 'NullReferenceException: Object reference not set to an instance of an object' here:
void hideTreeOfObjects(GameObject ob){
for (int i = 0; i < ob.transform.childCount; i++) {
//for some reason child = null in build, but child != null in preview
GameObject child = ob.transform.GetChild(i).gameObject; /*line 229*/
try{
child.GetComponent<MeshRenderer> ().enabled = false;
}catch(MissingComponentException){}
try{
if (child.tag != "lostdetector" && !VRmode){
child.GetComponent<Collider> ().enabled = false;
}
}catch(MissingComponentException){}
try{
child.GetComponent<LineRenderer> ().enabled = false;
}catch(MissingComponentException){}
hideTreeOfObjects (child);
}
}
This function disables some components for every GameObject in a hierarchy tree. It's called by this functions in the same script (UIManager.cs):
//[...]
public GameObject Indicators;
//[...]
void hideIndicators(){
hideTreeOfObjects (Indicators);
}
public void OnClickRepository(){
setMode (3);
PathItem.hideAllPathPoints ();
hideIndicators ();
selectedObject = null;
selectedObjectToCreate = null;
refreshUI ();
}
void Start () {
OnClickRepository ();
refreshUI ();
loadRepositoryUI ();0
}
This is the GameObject Indicators. It has only the transform component:
The GameObject Indicators is assigned properly in the inspector of the GameObject which uses the UIManager component:
Why is this happening?
Answer by jormaje · Apr 26, 2018 at 02:46 PM
I've solved it by catching the NullReferenceException. The problem was that Unity throws diferent exceptions in preview and in build. In preview I was getting the MissingComponentException when I was using a function of an inexistent component, but not the NullReferenceException.
So at the end all component function calls like
try{
child.GetComponent<MeshRenderer> ().enabled = false;
}catch(MissingComponentException){}
have turned into this
try{
try{
child.GetComponent<MeshRenderer> ().enabled = false;
}catch(NullReferenceException){}
}catch(MissingComponentException){}
But there are better solutions to enable/disable components for all the descendants of a specified object, like this one
public void Test2(GameObject ob)
{
MeshRenderer[] list = ob.GetComponentsInChildren<MeshRenderer>();
Debug.Log("Found: " + list.Length);
foreach (MeshRenderer rend in list)
{
Debug.Log("Disabling: " + rend.name);
rend.enabled = false;
}
}
Follow this Question
Related Questions
Unity Build nullReference, but editor sees through it! 1 Answer
Bogus Null Reference in Build only,Bogus Phony NULL REFERENCE in BUILD ONLY (works in editor) 0 Answers
Input Working in Editor but not in Build 0 Answers
Null Reference Exception in iOS build for some users. Not in Editor and cannot duplicate 0 Answers