Cannot alter MonoBehaviour state variables

Unity 4.6. I have a controller script which is spawning hazards. It does this through GameObject.Instantiate, whose return value is being stored and then manipulated, like so.

GameObject thingy = (GameObject)Instantiate (hazard, spawnPosition, spawnRotation);

I then manipulate the objects attached to this GameObject through the GameObject.GetComponent().

These manipulations are successful for Unity standard object types, such as TextMeshes

thingy.GetComponent<TextMesh>().text = currentWord;

However, when I attempt to alter the state of script objects that inherit from MonoBehaviour, this process fails, in a silent and inconsistent way. When I access the script object, by type, from thingy.GetComponent(), I am returned a mutable object. I can perform the following:

`thingy.GetComponent().dxn = “down”;

Debug.Log (thingy.GetComponent().dxn); //returns “down” `

However, this does not alter the dxn property of the instance of HazardMover attached to the instantiated object that shows up in the Inspector, and in the game.

There is, apparently, a level of indirection between what is returned by GetComponent and what is actually ‘in the game’. I don’t understand it, and I need to permute the HazardMover. I can permute the HazardMover if I access it by tag name, but this is a problem because to do this I have to iterate through all hazard GameObjects, which is not good. What’s going on?

I’m not sure you’re using the GetComponent function correctly.

YourScript script = gameObject.GetComponent<YourScript> ();
script.yourVariable = newValue;

The answer to this was a lot simpler than I expected, and orthogonal to my train of thought. I had set dxn to “up” in the prefab start() method (along with setting it in the editor - a messy and bad idea), and that method was running after the instantiation code in the controller.

oops.