I'd like my object to be active only when space key is NOT pressed
Hi, I'm new to Unity and Unity Forums, and I'd like to make my GameObject, called "trou" and well dragged in my inspector, disappear when the space bar is pressed.
But when I run the scene, I press space bar once and my object disappears forever, without being set to active when I unpress the key.
I'm on MacOS, with Visual Studio and Unity 19.4.20f1
I don't know why but I can't create any project with 20 versions, it just creates empty folders.
Thank you for helping me ^^
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DisplayNone : MonoBehaviour
{
public GameObject trou;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.Space))
{
trou.SetActive(false);
}
if (Input.GetKey(KeyCode.Space) == false)
{
trou.SetActive(true);
}
}
}
Answer by Neengash · Mar 04, 2021 at 09:39 AM
Could it be that you added this code as a component of the same object you are referencing ?
Keep in mind that an inactive gameObject stops executing it's code (since it's not "there" anymore).
I'd recommend creating an object "manager" (or whatever) which will have this code as its component, and then activate and deactivate a different object (cube for example) in the escene.
Bonus Track: Minor recommendations on the update Code
1) Use if-else if you want to check the opposite:
if (Input.GetKey(KeyCode.Space))
{
trou.SetActive(false);
}
else
{
trou.SetActive(true);
}
2) Unify it in a single sentence (if it doesn't get too confusing for you):
trou.SetActive(!Input.GetKey(KeyCode.Space));
Your answer
Follow this Question
Related Questions
How do I save separate keycodes presses at same time and store for use later in update? 0 Answers
Using one key only, change bool to true or false depending on it's current value 2 Answers
How to make custom input key presses 0 Answers
I'm trying to make the collision work. But... 2 Answers
How to change the Bool for only a single prefab GameObject creating with Instantiate? 2 Answers