- Home /
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!
Answer by Olie · Nov 10, 2010 at 06:05 AM
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.
sorry, retard here. Can you make this a little clearer with regards the variables in scripts. Which variable is inside which script? var theBlockType is in script "blxScript" or is ii in blxScript?
Answer by Eric5h5 · Nov 10, 2010 at 02:47 AM
You need to use GetComponent. Variables are not properties of GameObjects or Transforms, they are properties of scripts.
Your answer
