I'm doing settings section in my game, and there is a screen mode dropdown. I did 2 variables of dropdown, because when i try match dropdown variable and dropdown game object, it doesn't work. So, i match dropdown game object as GameObject, then i get dropdown component from dropdown game object by GetComponent. But, unity gives me an error: NullReferenceException: Object reference not set to an instance of an object What did i do wrong? There is the code:
public GameObject ddgo;
public Dropdown dd;
void Start() {
dd = ddgo.GetComponent<Dropdown>();
}
public void DDScreenMode() {
if (dd.value == 0) {
Screen.fullScreen = true;
Debug.Log("Dropdown value fullscreen!");
}
if (dd.value == 1) {
Screen.fullScreen = false;
Debug.Log("Dropdown value window!");
}
}
CodePudding user response:
Check if the dropdown component is on the ddgo gameobject not a child of it (if it is a child use GetComponentInChildren<Dropdown>()
instead), if it is all good check if you gave ddgo the right gameOBject
CodePudding user response:
.GetComponent<Dropdown>()
can only get gameObject's own component.
If you want to get component in child gameOjbect,
you should use GetComponentInChildren<T>()
instead of GetComponent<T>()
Check if GameObject ddgo
has Dropdown
script.