Reputation: 311
I'm a beginner in Unity and C#. I tried building a basic game where the GameObject's presence in the scene is toggled when a key is pressed. The GameObject does disappear when I press "Space", but it never appears when I press the same key again. The following is the code.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour {
private GameObject aj;
private bool flag = true;
void Start () {
aj = GameObject.FindGameObjectWithTag("robo");
}
void Update () {
if (Input.GetKey(KeyCode.Space))
{
flag = !flag;
aj.SetActive(flag);
}
}
}
Please let me know where the error lies.
Upvotes: 1
Views: 1223
Reputation: 1309
Posting this as answer for future viewers:
The main reason that the gameobject doesn't reappear is because when you turn off the object, the script attached to it is disabled as well. In order to fix this, you must have the script to disable it, on a different object. I usually use a manager object which is just an empty gameobject with scripts on it.
A secondary issue in your code is that you're using if(Input.GetKey(KeyCode.Space))
in update which will try to change it every frame. Change it to if(Input.GetKeyDown(KeyCode.Space))
to have it only be true on the first frame pressed.
Upvotes: 3
Reputation: 121
From a first view the code seems correctly, the only problem that I could figure it out is that you disable the object where the script is placed or his parent, and so the script won't be executed the second time.
P.s. I recommend you to not use that "flag" variable, instead would be more precise to use the GameObject.activeSelf attribute.
Upvotes: 1