Thursday, April 19, 2018

22. Saving data

We use a root Node and attach a script. We have 2 childs of Node, a Button and a Label.


We can use $ instead of get_node. We can save data by using File methods, such as store_line for saving a string and newline. The save will be done when button is clicked.


This script is attached to the Node.



extends Node

var label
var button
var pos

func _ready():
    label = $Label
    label.rect_position = Vector2(10,10)
    pos = get_viewport().get_mouse_position()
    label.set_text("Pos: " + str(pos))
    button = $Button
    button.rect_position = Vector2(50,50)
    button.set_text('Save')
    set_process_input(true)

func _input(event):
    if event is InputEventMouseButton:
        pos = event.position
        label.set_text("Pos: " + str(pos))

func _on_Button_pressed():
    var file = File.new()
    file.open("res://save_pos.dat", file.WRITE)
    file.store_line(str(pos))
    file.store_line('Another line')
    file.close()


This is a possible content of the file:

(58, 59)
Another line


No comments:

Post a Comment