toogle key in unity code example
Example 1: unity key toggle
public GameObject ON;
public GameObject OFF;
public KeyCode Interact = KeyCode.F;
private bool On_Off = false;
private void Update()
{
if (Input.GetKeyDown(Interact))
{
while (true)
{
if (On_Off == false)
{
ON.SetActive(true);
OFF.SetActive(false);
On_Off = true;
break;
}
if (On_Off == true)
{
ON.SetActive(false);
OFF.SetActive(true);
On_Off = false;
break;
}
}
}
if (On_Off == false)
{
ON.SetActive(false);
OFF.SetActive(true);
}
if (On_Off == true)
{
ON.SetActive(true);
OFF.SetActive(false);
}
}
Example 2: unity key toggle
public GameObject ON;
public GameObject OFF;
public KeyCode Interact = KeyCode.F;
private bool On_Off = false;
public IEnumerator Toggle()
{
if (Input.GetKeyDown(Interact))
{
while (true)
{
if (On_Off == false)
{
ON.SetActive(true);
OFF.SetActive(false);
On_Off = true;
break;
}
if (On_Off == true)
{
ON.SetActive(false);
OFF.SetActive(true);
On_Off = false;
break;
}
}
}
if (On_Off == false)
{
ON.SetActive(false);
OFF.SetActive(true);
}
if (On_Off == true)
{
ON.SetActive(true);
OFF.SetActive(false);
}
}
private void Update
{
Toggle();
}