NullReferenceException when referencing to another class
Hello all
Created new project. Made a cube and a sphere.
Created script AAA and attached it to Cube.
Created script BBB and attached it to Sphere
Class BBB:
public class BBB : MonoBehaviour {
public bool Test = true;
}
Class AAA:
public class AAA : MonoBehaviour {
private BBB bbb;
void Start ()
{
bbb = GetComponent<BBB>();
Debug.Log(bbb.Test);
}
}
Debug.Log trows NullReferenceException. Why?
Answer by getyour411 · Dec 11, 2016 at 11:08 PM
"bbb" needs something like
GameObject.FindObjectByTag("Sphere").GetComponent...
or make bbb decl public and drag/drop reference to Sphere in the Inspector field that will appear.
Answer by denmla1000 · Dec 13, 2016 at 07:07 PM
Tnx, but I was not clear. I know how to make this work other ways.
My question was why is this not working.
I am C# beginner and in combination with Unity infrastructure it only gets complicated.
Both classes are public and in same Visual Studio project. I would like someone to try to explain to me why is this class "visible" by project and yet not accessible by other classes.
Your answer
![](https://koobas.hobune.stream/wayback/20220612102500im_/https://answers.unity.com/themes/thub/images/avi.jpg)