I have currently made inventory which is opened by pressing B and closing with same button.
On awake it starts calling the else statement, i saw it by debugging. When i press B, the inventory just flashes and closes cause the else statement is called everytime. This is very basic, have i missed something?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Inventory : MonoBehaviour {
public RectTransform inventory;
void Start ()
{
}
void Update ()
{
if (Input.GetKeyDown (KeyCode.B) && Time.timeScale == 1)
{
inventory.gameObject.SetActive (true);
}
else
{
inventory.gameObject.SetActive (false);
Debug.Log("Closing Inventory");
}
}
}
You haven’t missed anything. It’s functioning exactly as you described in this portion of your post.
An empty else statement will run code whenever the conditions of the matching if statement are no longer met. Additionally by putting it into an Update() function it will be called every single frame. Because GetKeyDown only returns true for a single frame it was only executing the code in the if statement for one single frame. All other frames were immediately closing it again.
Making the code function the way you intended it simply requires removing the code within the else segment and simplying modifying the code within the if segment to reverse or flip the current state of the inventory.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Inventory : MonoBehaviour {
public RectTransform inventory;
void Update()
{
if (Input.GetKeyDown (KeyCode.B) && Time.timeScale == 1)
{
inventory.gameObject.SetActive (!inventory.gameObject.activeSelf);
}
}
}