x


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?

more ▼

asked Oct 28 '10 at 11:46 PM

LifeSizeDeity gravatar image

LifeSizeDeity
127 15 17 26

(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

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.

more ▼

answered Oct 29 '10 at 12:56 AM

Molix gravatar image

Molix
4.8k 16 27 66

What I ended up doing was changing the Start() to Awake(), kinda cheap trick, but I gots deadlines approaching fast. Thanks for your help.

Oct 29 '10 at 01:20 AM LifeSizeDeity
(comments are locked)
10|3000 characters needed characters left

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.

more ▼

answered Oct 29 '10 at 12:56 AM

Adam Rademacher gravatar image

Adam Rademacher
1.1k 1 3 19

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x3328
x1093
x263
x46

asked: Oct 28 '10 at 11:46 PM

Seen: 772 times

Last Updated: Oct 29 '10 at 12:41 AM