- Home /
If and else applying two states of a variable - complaining that the variable is duplicate?
Hello. This is an odd bug that I can't get to work. Here is my script:
var NormalBall : Rigidbody;
var BonusBall : Rigidbody;
function Start () {
}
function SpawnBall(){
var choice = Random.Range(1, 6);
if (choice == 1){
var TypeOfBall = BonusBall;
}
else {
var TypeOfBall = NormalBall;
}
var clone : Rigidbody;
clone = Instantiate(TypeOfBall, transform.position, transform.rotation);
}
My problem is that it gives me the error that the variable TypeOfBall is a duplicate,
Assets/Scripts/BallPart.js(11,5): BCE0067: There is already a local variable with the name 'TypeOfBall'.
Hmm. It also claims that
The prefab you want to instantiate is null.
I have it set in by dragging it into the box, yet it still says it's null. I would really appreciate some input, as I know perfectly well that it's a duplicate, and that's what I want.
Thank you!
-Keavon
Answer by Jessy · Dec 30, 2010 at 04:29 AM
No, you really should declare the variable with the var keyword; what you have is ambiguous. However, your entire function could be consolidated into this:
Instantiate(Random.Range(1, 6) == 1 ? bonusBall : normalBall);
You'll notice I renamed the variables; camelCase starting with lowercase for variables is the convention. UpperCase is for class, struct, and function names.
If you don't like the conditional operator, this would be the way to handle it:
private var typeOfBall; function SpawnBall() { if (Random.Range(1, 6) == 1) typeOfBall = bonusBall; else typeOfBall = normalBall;
// ...
}
There doesn't seem to be a reason to make that a global variable; I would keep it local. In JS you can declare the variable inline: "`if (Random.Range(1, 6) == 1) var typeOfBall = bonusBall; else typeOfBall = normalBall;`".
I noticed that. It doesn't make any sense to me, why that works, so I didn't suggest it. I'd love a link about it.
Are you saying that my origional script is global? I don't see anything global there. Thanks for the answers, but for simplicity's sake, I think I will keep it as it is, as it works fine.
I disagree. Your code is very long, making looking through further lines of code a chore, and prohibiting quick comprehension. As for it being global, I don't know if that's the right term for it; Eric is saying that the way I showed you, the variable will be accessible outside of the function. And I'm saying I don't understand how his example compiles, even though I like it better.
Answer by Keavon · Dec 30, 2010 at 04:24 AM
Oops. I found my mistake. The problem is that I wrote var before the TypeOfBall variable's, so it should be like this:
var NormalBall : Rigidbody;
var BonusBall : Rigidbody;
function Start () {
}
function SpawnBall(){
var choice = Random.Range(1, 6);
if (choice == 1){
TypeOfBall = BonusBall;
}
else {
TypeOfBall = NormalBall;
}
var clone : Rigidbody;
clone = Instantiate(TypeOfBall, transform.position, transform.rotation);
}