- Home /
C# Children and SubChildren Null Reference Exception
Hi everyone, in one of my scripts I'm getting a null reference exception and I'm trying to figure out why. The console says it's coming from line 9. I have two Transform Arrays someTransformArray1 and someTransformArray2. Both of them have children and subchildren. I want to make it so someTranformArray1's subchildren's sharedMesh equals someTranformArray2's subchildren's sharedMesh. Any idea what is causing this null reference exception?
public Transform[] someTransformArray1;
public Transform[] someTransformArray2;
void Awake(){
foreach (Transform child1 in someTransformArray1)
foreach (Transform child2 in someTransformArray2)
foreach (Transform subchild1 in child1)
foreach (Transform subchild2 in child2)
subchild1.GetComponent<MeshFilter>().sharedMesh = subchild2.GetComponent<MeshFilter>().sharedMesh;
}
is this all the code? you should just post your code for better answers. childCurrent is not assigned it's telling you.
That was a mistake in my code. I fixed the name to child1 like it's suppose to be.
Answer by Em3rgency · Jun 29, 2013 at 09:10 PM
Add an
if(subchild1 != null && subchild2 != null)
right above line 9, and you will be dandy. (It wont change the fact that this does not find any subchild1/2 in childCurrent or childOriginal, but it will get rid of that error)
Also, you seem to be running a cycle in a cycle in a cycle in a cycle. Are you SURE that's what you wan't to be doing?
I need to access children of children so yes. I do think this way of finding them is rather redundant. Do you know an easier and more efficient way of doing this?
Well, no, that's about right, but children of children would only get you 2 levels (1 loop for the children of the object, second loop inside that for the children of children). Not full blown 4. :)
I'm still getting the null reference Exception.
public Transform[] someTransformArray1;
public Transform[] someTransformArray2;
void Awake(){
foreach (Transform child1 in someTransformArray1)
foreach (Transform child2 in someTransformArray2)
foreach (Transform subchild1 in child1)
foreach (Transform subchild2 in child2)
if(subchild1 != null && subchild2 != null)
subchild1.GetComponent<$$anonymous$$eshFilter>().shared$$anonymous$$esh = subchild2.GetComponent<$$anonymous$$eshFilter>().shared$$anonymous$$esh;
}
Ok wait, do you create the someTransformArray1 and someTransformArray2 anywhere? Just declaring it like that is not enough.
I found what was causing the Null Reference exception. I needed to check if subchild1 and subchild2s' $$anonymous$$eshFilters were null not the subchildren themselves.
if(subchild1.GetComponent<$$anonymous$$eshFilter>() != null && subchild2.GetComponent<$$anonymous$$eshFilter>() != null)
Your answer
Follow this Question
Related Questions
C# SetActive GameObject Array 2 Answers
C# Need Help Refining Ricochet Script 1 Answer
C# locking Main Camera's Rotations 1 Answer