Can't access prefab's variables, once instantiated.

I'm trying to instantiate a game object, then set its variables before it runs `Start()`. So I have code like this:

var myPrefab : GameObject;

function Start() {
    types = BlockTypes.GetValues(BlockTypes);
    var xfrm : Transform = transform;
    // xfrm.Translate(xx, yy, zz), etc...
    oneBlox = Instantiate (myPrefab, xfrm.position, transform.rotation);
    oneBlox.theBlockType = someIntValue;
    oneBlox.transform.parent = this.transform;
}

The problem I'm having is that this line:

oneBlox.theBlockType = someIntValue;

is generating an error at runtime:

MissingFieldException: Field 'UnityEngine.Transform.theBlockType' not found.
[stack trace snipped]

What's the correct syntax to (a) instantiate an object of type MyPrefab, then (b) set one of the prefab's variables?

Thanks!

2 Answers

2

You need to use GetComponent. Variables are not properties of GameObjects or Transforms, they are properties of scripts.

Thanks, Eric5h5. Your answer was technically correct but, as a n00b, I found it frustrating that so many answers on this site talk about the theory but not the actual code, so I'm going to give the answer I think that others with this question will want. Here's the working code:

var iblxPrefab : GameObject;

function Start() {
    var oneBlox : GameObject;
    oneBlox = Instantiate (iblxPrefab, xfrm.position, transform.rotation);

    var bloxScript = oneBlox.GetComponent("blxScript"); // name of script without the ".js" at the end.
    bloxScript.theBlockType = ii;                       // name of variable in script.
}

Key bits: (a) to instantiate a prefab, the syntax is:

    var oneBlox : GameObject;
    oneBlox = Instantiate (iblxPrefab, xfrm.position, transform.rotation);

(for some reason, I was unable to get the all-in-one-line version of this to work, but that may be me, rather than a Unity limitation) and (b) to access an object's script's variables, the syntax is this:

    var bloxScript = oneBlox.GetComponent("blxScript"); // name of script without the ".js" at the end.
    bloxScript.theBlockType = ii;                       // name of variable in script.

You should mark this answer as "accepted" so the auto-bump bot doesn't bump this question again.

Done. Thanks, Tetrad.