Hello, I have 2 scripts as follows:
// Script_A.cs
using UnityEngine;
using System.Collections;
public class Script_A : MonoBehaviour
{
public float number_One = 1;
public class Script_A_Subclass : MonoBehaviour
{
public float number_Two = 2;
}
}
// Script_B.cs
using UnityEngine;
using System.Collections;
public class Script_B : MonoBehaviour
{
public Script_A firstScript;
public Script_A.Script_A_Subclass firstScriptSubclass;
void Update ()
{
firstScript.number_One = 100001;
firstScriptSubclass.number_Two = 22222;
}
}
The issue I’m having is I can access from Script_B.cs the variable number_One but not number_Two. Does Unity3D allow access to subclass variables like this? If so, how do you access them? I’m getting an error that “NullReferenceException: Object reference not set to an instance of an object
Script_B.Update () (at Assets/Script_B.cs:14)”.
Thanks again.
You haven’t initialized the variables, hence the NullReferenceException
// Script_A.cs
using UnityEngine;
using System.Collections;
public class Script_A : MonoBehaviour
{
public float number_One = 1;
public class Script_A_Subclass : MonoBehaviour
{
public float number_Two = 2;
}
}
// Script_B.cs
using UnityEngine;
using System.Collections;
public class Script_B : MonoBehaviour
{
public Script_A firstScript;
public Script_A.Script_A_Subclass firstScriptSubclass;
void Start ()
{
// Initialize here --------------------------------------
firstScript = new Script_A();
firstScriptSubclass = Script_A.Script_A_Subclass();
}
void Update ()
{
firstScript.number_One = 100001;
firstScriptSubclass.number_Two = 22222;
}
}
Ok so I’ve been bashing my head here trying to figure this coding out. Thank you all for the help. I’ve added the following to Script_B.cs:
void Start ()
{
// add components here
firstScript = cube.AddComponent<Script_A> () as Script_A;
}
That code loads the script perfectly onto my test cube gameObject but I can only access the parent class in Script_A.cs. All the Script_A.cs child class are untouchable and blind to Script_B.cs.