- Home /
Changeing a Transform var
So, my code goes somthing like this:
var ObjectA:Transform var ObjectB:Transform var ObjectC:Transform var InstantiateObject
function Update(){
if (FireRequirements){ var ClonedObject = Instantiate(InstantiateObject, transform.position, Quaternion.identity) }
if (SpawnObjectA){ InstantiateObject = ObjectA }
if(SpawnObjectB){ InstantiateObject = ObjectB }
if (SpawnObjectC){ InstantiateObject = ObjectC } }
My problem comes when I get an error saying that I haven't defined InstantiateObject to start off with. When I do define InstantiateObject to start with, it won't change to Objects A, B, or C.
Congratulations if you had the patience to read all of of that, And thanks in advance to anyone who helps.
Answer by The_r0nin · Nov 26, 2010 at 12:45 AM
First, this would have been easier to read if you had selected all of the code and then hit the "zeroes and ones" (i.e. code) button.
Secondly, try explicitly typing your object, like:
var instantiateObject: GameObject;
The other issue might be that you try to instantiate your object before you've selected which object it will be (you hit the Instantiate "if" before you hit the Select "if"s). If your code above is in that order in your program, you might want to reverse it. Personally, I don't know why you wouldn't just select and Instantiate at the same time:
if (fireRequirements){
var clonedObject: GameObject = objectDefault; // set which object you want if none are selected.. i.e. the default
if (spawnObjectA){
clonedObject = Instantiate(objectA, transform.position, Quaternion.identity)
}
else{
if (spawnObjectB){
clonedObject = Instantiate(objectB, transform.position, Quaternion.identity)
}
else{
if (spawnObjectC){
clonedObject = Instantiate(objectC, transform.position, Quaternion.identity)
}
}
}
}
Another hint: variable names normally begin with a lower case letter and functions with an upper case letter (see my code). This isn't required, but it will help you at a glance (if you see "IsSpawned" you will know you forgot the "()" for the function, instead of not being sure you didn't mean the variable "isSpawned").
Note that if all three "spawnObject"s are true (or not null), three different objects will be spawned with that code. If you want just one object to spawn, make a variable to set which object is desired (i.e. 1, 2, or 3) and use a switch/case to choose between them.
Your answer
