I’m looking to use one button to be able to toggle between three states. Currently, I’ve got the following code:
function Update() {
if (Input.GetKeyDown("b")) {
renderer.enabled = !(renderer.enabled);
}
}
That essentially hides one object and makes the other visible (two state). But now, my client wants three objects…
So, by hitting the “b” three times, you move through progressively making one object visible and hiding the other two. Any tips on this?
TIA
It’s not pretty, but this should do the job:
var state = 0;
function Update () {
if (Input.GetKeyDown("b")) {
switch (state) {
case 0:
obj1.renderer.enabled = true;
obj2.renderer.enabled = false;
obj3.renderer.enabled = false;
state++;
break;
case 1:
obj1.renderer.enabled = false;
obj2.renderer.enabled = true;
obj3.renderer.enabled = false;
state++;
break;
case 2:
obj1.renderer.enabled = false;
obj2.renderer.enabled = false;
obj3.renderer.enabled = true;
state = 0;
break;
}
}
}
Hey thanks much for the help. I am completely unaware of this ‘switch’ stuff…great to learn.
It actually throws an error when it tries to compile:[quote]
‘renderer’ is not a member of ‘System.Type.’
[/quote]
Any ideas what needs to be adjusted there?
It could also have been done with the if/else if/else structure - equivalent to switch
if(Input...)
if(state==0)...
else if(state==1)...
else ...
Make sure that your references to the objects in question are actually GameObjects, otherwise it will throw an error.
Thanks again for the posts. It actually throws the error on compiling - before I’ve assigned any gameobjects. I do change the obj1 to a boiler1 (etc…) var that I call out at the beginning. Could that be the problem?
What is your declaration for the objects? JavaScript in Unity (aka UnityScript) determines the type of an object automatically, but it seems to be missing it here. To force the type of the object you use a colon:
var obj1 : GameObject;
Then that object should be visible in the inspector and you can assign the appropriate object from you scene to it.
It shouldn’t matter what you call it, obj1, boiler1, etc., so long as it is a GameObject.
Thanks much! I really appreciate your help.