- Home /
How to toggle between 3 different settings
What I am trying to do is make pressing Z on the keyboard toggle between 3 values. I cannot figure out how I would do this.
So:
value is 1 > Z is pressed > value toggles to 2 > Z is pressed > value toggles to 3 > Z is pressed > value toggles back to 1
Answer by XienDev · Nov 01, 2012 at 09:56 AM
using UnityEngine;
using System.Collections;
public class first : MonoBehaviour {
private int z = 1;
void Update () {
if (Input.GetKeyDown(KeyCode.Z))
{
z = (z % 3) + 1;
print (z);
}
}
}
Perhaps I'm missing something because I'm not using C, I'm using javaScript.
$$anonymous$$aybe I should just switch to C...
Nope still does not work... I press Z and it prints 2, then 3, then 1, but then it stops printing after that. No idea what I'm doing wrong.
Is the object getting destroyed? If that code executes then it will always cycle between 1 and 3.
Answer by XienDev · Nov 01, 2012 at 09:48 AM
z = (z % 3) + 1;
and don't forget to make it 1; at default
Thank you that worked but the only problem is that it stops working once it gets back to 1. I want it to continue to cycle through whenever Z is pressed.
Answer by suresh.murugesan · Nov 01, 2012 at 06:11 AM
check the time difference between the first and next button . you can solve it easily ... Time.deltaTime use this..
Answer by Griffo · Nov 01, 2012 at 08:22 AM
Try this, but I don't think Fattie will like it (else if) .. ;)
#pragma strict
private var onePress : boolean = true;
private var twoPress : boolean = false;
private var threePress : boolean = false;
function Start () {
}
function Update () {
if (Input.GetKeyDown ("z")){
keyPress();
}
}
function keyPress(){
if (onePress && !twoPress && !threePress){
onePress = false;
twoPress = true;
threePress = false;
// Do Stuff
print("Button press 1");
}else if (!onePress && twoPress && !threePress){
onePress = false;
twoPress = false;
threePress = true;
// Do Stuff
print("Button press 2");
}else if (!onePress && !twoPress && threePress){
onePress = true;
twoPress = false;
threePress = false;
// Do Stuff
print("Button press 3");
}
}
I wouldn't like it either ;). Not because of the else if's but because it would be easier changing a integer value :)
Answer by Althaen · Nov 03, 2012 at 08:30 AM
I found out why it stops at 1...
The code:
z = (z % 3) +1;
It only works 3 times. If I set it to 5 it works 5 times. If I set it to 57 it works 57 times.
How do I make it go between 1-3 forever?
Your answer
Follow this Question
Related Questions
Weapon pick up and switching script 2 Answers
Weapon swapping in-game 2 Answers
Could anyone help me with .js code to be able to pickup a flashlight and turn it on and off -1 Answers
making a named script update 1 Answer
Help With Remote Explosive 1 Answer