im getting the error "Invalid set index 'text' (on base: 'Label') with value of type 'Nil' " and idk why

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

im trying to make interactable objects display text based on what key should be used to interact with it. when i run the game it opens fine but when i look at one of the objects it crashes and gives me the error.

here are the scripts:

(interactable.gd)

class_name Interactable
extends StaticBody

export var prompt_message = "Interact"
export var prompt_action = "interact"


func get_prompt():
	var key_name = ""
	for action in InputMap.get_action_list(prompt_action):
		if action is InputEventKey:
			key_name = OS.get_scancode_string(action.scancode)
		return prompt_message + "\n[" + key_name + "]"

(interactRay.gd)

extends RayCast


onready var prompt = $prompt


# Called when the node enters the scene tree for the first time.
func _ready():
	add_exception(owner)

func _physics_process(delta):
	prompt.text = ""
	if is_colliding():
		var detected = get_collider()
		
		if detected is Interactable:
			prompt.text = detected.get_prompt()
	
	
:bust_in_silhouette: Reply From: zhyrin

get_prompt()'s only return statement is in a loop, if you iterate over an empty container, you’ll never enter the loop, your desired return statement will never be reached.
Instead the function will return null.

i still quite new so im not sure what this means. could you please explain this a little simpler

turtilla955 | 2023-02-10 22:48

The point is, you need to make sure your get_prompt() method returns something in all cases. Currently, it will only return a value under certain conditions.

So, you need to change get_prompt() to look something like this:

func get_prompt():
    var result = ""
    for action in InputMap.get_action_list(prompt_action):
        if action is InputEventKey:
            key_name = OS.get_scancode_string(action.scancode)
            result = prompt_message + "\n[" + key_name + "]"
            break
    return result

That will return an empty string by default, or your constructed message if an input match is found.

jgodfrey | 2023-02-11 00:46

this works thank you

turtilla955 | 2023-02-11 13:14