x


Using GetComponent() to change Script Variables, but does nothing

I'm having trouble trying to change values in another script, and I'm clueless as to why. The code below is in the Start function of a script attached to the main camera:

GameObject ins = (GameObject) Instantiate(Resources.Load(@"Cube"));
tileEngineTile n = ins.GetComponent<tileEngineTile>();

n.test = "Good";

When running: I can see the object has been initialised in the hierarchy, but the test variable is set to "Bad" (which is set in the Start() method of the tileEngineTile script) in the inspector. None of the other methods/variables I've written work either, and I haven't got a clue as to why. The test variable as well as the other methods are all public, and I haven't got a clue as to what's going on. Does anyone have any ideas?

more ▼

asked May 06 '12 at 08:40 PM

AdmiralJonB gravatar image

AdmiralJonB
2 1 1 1

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

2 answers: sort oldest

The start method is called the next frame after you instantiated the object. So it's overwriting any change you do right after the instantiation. Awake is called immediately when the object got created / instatiated. Awake is executed even before the Instatiate function returns. Do local initialization which doesn't require external references in Awake or direct as field initializer like so:

//C#
public string test = "Bad";

// UnityScript
public var test = "Bad";

Start should be used when you want to access other objects / components since it's guaranteed they are available and created when Start is called. The Start-function-calling is part of the main game loop. If an object has been created in the last frame the Start method is called at the beginning of the next frame.

more ▼

answered May 06 '12 at 08:54 PM

Bunny83 gravatar image

Bunny83
45.5k 11 49 207

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

The Start() method of the newly instantiated object is executed at some point after the Start() method of the main camera's component. It's not executed as part of the instantiation.

Hence, what happens is that the object is instantiated, then its member variable is set to "Good", and then its own Start() method sets the variable back to "Bad".

more ▼

answered May 06 '12 at 08:53 PM

Jacek_Wesolowski gravatar image

Jacek_Wesolowski
151 1 1 2

(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:

x406

asked: May 06 '12 at 08:40 PM

Seen: 687 times

Last Updated: May 06 '12 at 08:54 PM