- Home /
Finding Scroll Rect by name keeps throwing Null Reference Exception
Hey guys. I have 2 pieces of a code where I first find a ScrollRect in a scene, and another piece where I add/delete children of that Scroll Rect.
private void OnLevelWasLoaded()
{
if (SceneManager.GetActiveScene().name == "Menu")
{
SkirmishRect = GameObject.Find("SkirmishScrollRect").GetComponent<ScrollRect>();
}
}
This Section finds the ScrollRect in question for the variable SkirmishRect perfectly.
public void AxiomLocation()
{
foreach (Transform child in SkirmishRect.transform)
{
Destroy(child.gameObject);
}
}
This piece however keeps throwing me a null reference error for SkirmishRect, despite the first piece of the code loading the correct game object.
Any help is greatly appreciated.
Answer by RobAnthem · Dec 27, 2016 at 11:40 PM
Change it to
SkirmishRect.GetComponent<Transform>()
I changed the second part of the code to
foreach (Transform child in SkirmishRect.GetComponent<Transform>())
Unfortunately I'm still getting the same error. Unless you are referring to a different part of the code
Answer by ElijahShadbolt · Dec 28, 2016 at 06:42 AM
Is AxiomLocation() called anytime before OnLevelWasLoaded() ? If so, it would be trying to access a null object before it is assigned. I could be totally wrong, this was just my first thought.
To be safe and avoid NullReferenceExceptions, I always put if(referenceVariable != null) {...}
around the code.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Bool not changing on button press 1 Answer
Add an iteration of OnClick methods 1 Answer
Best way of using sprites as text 0 Answers