- Home /
C# class public variables null in all methods but start()
I have variables declared in my class defined outside of a method, but when i use them in any method other than start(), the object references are null. It is like all the object references get broken. Why would this be? I used an int to test, and the value is changed in my start function and i can use object references in start(), but in other functions they are all null for some reason.
My script is instantiated on a prefab, and then i reference the script on the prefab using this code:
bObj = Instantiate(Resources.Load("BuilderPrefab") ) as GameObject;
b = bObj.GetComponent("Builder") as Builder;
b.setUpObj(positionOfQueue,new GameObject("dummyForBuilder"),false,this);
b.startBuild(15f);
the null reference should be a reference of dummyForBuilder's gameObject ? When does the exception occurs ?
sorry, the exception occurs inside the builder method setUp() and it complains about a script class variable i defined and used in start, but then it is "magically" null in other methods.
do you think you could give a run-able example that demonstrates this behavior?
Here is my code for my builder class:
//beginning of class (extends monobehavior)
public GameObject debugObj; //game object with script to be found public DebugGuiText debugGText; //script
//inside start
debugObj = (GameObject)GameObject.Find("Debug-gText");
//this passes the check for not being null
debugGText = (DebugGuiText)debugObj.gameObject.GetComponent("DebugGuiText");
//is not null as well
debugGText.permDebug("done with start method");
//shows text to guiText object, actually shows up and works
//update()
debugGText.permDebug("inside update method call");
//public void setUp(float n)
debugGText.permDebug("inside setUp()");
The behavior is that update is skipped (never executes, even if i omit the line of debugGText and put a test int and incriment it. Instantiate the builder and start() runs and prints out the message to the guiText object. When i call the setUp method, the game complains about a null reference at that line where permDebug is called. If i put an if statement to check if null and skip, it sucessfull skips and avoids the null reference. If i tell it to check if obj is null then execute permDebug, it gives a null reference.
What could cause this?
Based on the code you posted, debugGText is scoped inside the Start() method (only debugObj is a field). Is that true? If so it will go out of scope as soon as you leave.