- Home /
Having script accessing issues
I'm having problems with this working:
ObjectA has ScriptA attached to it
ScriptA
{
public doSomething();
}
ScriptB
{ private ScriptA refObject;
void Start() { refObject = GameObject.Find("ObjectA").GetComponent("ScriptA") as ScriptA; }
void makeRefObjDoSomething() { refObject.doSomething(); } }
When I call makeRefObjDoSomething(), Unity says "Object reference not set to an instance of an object", I thought this was a legal call?
Answer by Molix · Oct 29, 2010 at 12:56 AM
The error means that refObject is not set to anything. That means that either ScriptB.Start() was not called yet (e.g. if the object containing ScriptB was just Instantiated this frame), or, when it was called it did not find the object/script in question.
I'd pepper in some Debug messages (e.g. a Debug.Log("ScriptB.Start()");), and separate the GameObject.Find and GetComponent calls (in case the Find returns null. I'd also use the Type, rather than the string version of GetComponent, i.e. GetComponent(typeof(ScriptA)), or the generic version.
What I ended up doing was changing the Start() to Awake(), kinda cheap trick, but I gots deadlines approaching fast. Thanks for your help.
Answer by Adam Rademacher · Oct 29, 2010 at 12:56 AM
Try debugging refObject.gameObject.name immediately after you do the find command to make sure it's getting the component properly. If it's not finding the object properly, tweak the way you're looking for it by either using FindWithTag. If it is finding the object properly, go into debug mode in the editor to make sure something else isn't clearing the reference for some crazy reason, or that objectA isn't getting destroyed.