Godot Version
v4.2.1.stable.official [b09f793f5]
Question
My first attempt to implement a persistent player profile system using a resource. It appears to work. Am I on track?
profile_class.gd: (the resource script that defines the data structure, the data itself is contained in the instantiation of this class)
extends Resource
class_name ProfileClass
@export var PlayerName = "Guest"
@export var PlayerNameList = ["Guest"]
main.gd: (the initial execution script)
extends Node
var Profile: ProfileClass
var ProfileFileName = "user://profile.tres"
func _ready():
LoadProfile()
func _process( _delta):
if Input.is_key_pressed( KEY_ESCAPE):
get_tree().quit()
func LoadProfile():
if ResourceLoader.exists(ProfileFileName):
Profile = ResourceLoader.load(ProfileFileName)
else:
Profile = ProfileClass.new()
UpdateHud()
func SaveProfile():
ResourceSaver.save( Profile, ProfileFileName)
func _on_profile_line_edit_text_submitted(new_text):
Profile.PlayerName = $ProfileLineEdit.text
if !Profile.PlayerNameList.has( Profile.PlayerName):
Profile.PlayerNameList.append( Profile.PlayerName)
SaveProfile()
UpdateHud()
func _on_delete_button_pressed():
Profile.PlayerNameList.erase( $ProfileLineEdit.text)
Profile.PlayerName = "Guest"
SaveProfile()
UpdateHud()
func UpdateHud():
$ProfileLineEdit.text = Profile.PlayerName
$ProfileRichTextLabel.text = "Profile Data:\n\n" + Profile.PlayerName + "\n\n"
for name in Profile.PlayerNameList:
$ProfileRichTextLabel.append_text( name + "\n")
if Profile.PlayerName == "Guest":
$DeleteButton.hide()
else:
$DeleteButton.show()
main.tscn: (the only scene, the initial execution scene, included to list the nodes and show connections)
[gd_scene load_steps=2 format=3 uid=“uid://bhaju3nhyxot4”]
[ext_resource type=“Script” path=“res://main.gd” id=“1_xqy8h”]
[node name=“Main” type=“Node”]
script = ExtResource(“1_xqy8h”)
[node name=“PlayerLabel” type=“Label” parent=“.”]
offset_left = 40.0
offset_top = 18.0
offset_right = 89.0
offset_bottom = 41.0
text = “Player”
[node name=“ProfileLineEdit” type=“LineEdit” parent=“.”]
offset_left = 97.0
offset_top = 11.0
offset_right = 365.0
offset_bottom = 42.0
placeholder_text = “Player Name?”
[node name=“DeleteButton” type=“Button” parent=“.”]
offset_left = 371.0
offset_top = 12.0
offset_right = 430.0
offset_bottom = 43.0
text = “Delete”
[node name=“ProfileRichTextLabel” type=“RichTextLabel” parent=“.”]
offset_left = 5.0
offset_top = 49.0
offset_right = 1104.0
offset_bottom = 635.0
text = “Profile Data:”
[connection signal=“text_submitted” from=“ProfileLineEdit” to=“.” method=“_on_profile_line_edit_text_submitted”]
[connection signal=“pressed” from=“DeleteButton” to=“.” method=“_on_delete_button_pressed”]