Using Pickles to save game variable...

I try

import bgeimport pickle


cont = bge.logic.getCurrentController()
own = cont.owner
dat = own['check']


f = open('store.txt', 'wb')
pickle.dump(dat, f)
f.close()


own['check'] = dat



There aren’t any syntax errors in the console, but the variable doesn’t save… Can someone tell me how to fix this? I plan to use it to save a variable so I tell something in a different part of the game.

I use JSON as it’s easier to read by the human eye and check it’s OK:


import bge
import json

def save_file(my_data,filename):
    
    file = open(filename + ".txt", 'w')
    
    json.dump(my_data,file)
    
    file.close()     
                  
def load_file(filename):  
        
    file = open(filename + ".txt", 'r')

    my_data= json.load(file)    
        
    file.close()
    
    return my_data

A lot of people use with instead of file these days, maybe read up on it if you want to keep up to date (this is an old code snippet). You should also check out expand path if you’re not already using it.

If there is no console output I suggest to add a print statement to see if your code gets executed at all.

When you can verify it was executed, you may look where the file was written to.

It depends where store.txt is saved. I expect it is the blender application folder, as you haven’t provides an absolute path

Sent from my SM-G920F using Tapatalk

To make a path to a file in your game’s directory -instead of the blender application directory- you can use bge.logic.expandPath(’//store.txt’)

Can you explain this a bit more? I’m confused on how to implement it.

The BGE provides a method to refer to the path where your startup-Blend-file is located. You do that with “//”.

But this is BGE-syntax not Python syntax. So you need to let the bge parse the path string you provide before you use Python libraries on it. The conversion is done by bge.logic.expandPath.

“//SaveFiles/saveFile.storage” --> expandPath --> “C:/MyGames/MyGame/SaveFiles/saveFile.storage”

To implement, replace this:

f = open('store.txt', 'wb')

With this:

f = open(bge.logic.expandPath('//store.txt'), 'wb')

Okay thanks, I’ll try that!