Is there a way to get a sprite to show up after a random amount of time?

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

I am unsure of how to set a timer so then a sprite will appear randomly to the user. Also is it possible to create a limit of time (eg after 5 seconds but before 20)?

:bust_in_silhouette: Reply From: p7f

I assume you have a scene, with a script attached, and a sprite as a child node of that scene.

So you can hide it in ready, wait some time and then put it visible again.

func _ready():
    randomize()
    $Sprite.visible = false
    var t = rand_range(5,20)
    yield(get_tree().create_timer(t),"timeout")
    $Sprite.visible = true

This code, first runs randomize to initialize a seed for random generation. Then hides the sprite, after that, it generates a rando number between 5 and 20 (for the limits you asked, you can change them). After that, it creates a timer, with the timeout generated randomly befor that, and wait until it times out.
After that, it puts the sprite visible again

Thank you so much! The only thing that didn’t work was the $Sprite.visible = false (vise versa) but that was fixed by just using hide() instead!

Cakee | 2020-09-07 12:57

Thats strange… i tested with $Sprite.visible = false just now and it worked. IDK why is not working on your side.
Anyways, glad to help!

p7f | 2020-09-07 13:00