How to change the button visibility on a certain codition?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By huntariel

Hi All,

I’m a total beginner for both coding and game dev. I’m trying to create a simple child book with with various selection options on the way as a first project.

I create pages as different scenes and change them according to selection.

In a particular spot, I have 2 answers (buttons) and I want to hide or show them in certain condition. (condition is visit another scene previously or not).

Could you please help how can I do it?

Your help is really appreciated.

:bust_in_silhouette: Reply From: Eric Ellingson
func _ready():
     $Button1.visible = should_show_button_1()
     $Button2.visible = should_show_button_2()

func should_show_button_1() -> bool:
     return some_condition

func should_show_button_2() -> bool:
    return some_other_condition

should_show_button_1() and should_show_button_2() just need to return true or false depending on if the button should show (i don’t know how you are determining it). The key here is the button’s .visible property.

Thank you for your answer.

I believe this is the solution I’m looking for.

Thing is, I still don’t know how to place the conditions.

The conditions are;

Button1 is visible if a certain page (scene) -lets call it Page00X- is already visited (opened) before.
Button2 is visible if not

Could you please assist how can I add these conditions to the code?

huntariel | 2019-10-28 22:11

If you’re not saving that state somewhere, you’ll have to start. One option is to add an autoloaded script. This is a script that is loaded… wait for it… automatically - and is available from every other script. You could call it or something. In that script you can have something like:

extends Node

var visited_levels = {
    "level_1": false,
    "level_2": false,

Once that is registered as an autoloaded script, you can use it like this:


func _ready():
    GameState.visited_levels.level_1 = true

Then, back to the original question, you could do something like:

func _ready():
     $Button1.visible = GameState.visited_levels.level_1
     $Button2.visible = GameState.visited_levels.level_2

Here you wouldn’t need to create those extra functions because already holds the boolean value you are looking for.

Eric Ellingson | 2019-10-28 22:28

autoloading reference if you need it: Singletons (AutoLoad) — Godot Engine (3.1) documentation in English

Eric Ellingson | 2019-10-28 22:29

You just solve 2 of my problems, and 1 I don’t even know it exists!

So many thanks again.

huntariel | 2019-11-02 17:32