save and load one specific object rotation and position

can any one post a .blend file that save and load one specific object rotation and position
thank you for any help

This is the third thread you ask for help about save and load, try to keep with just one, it will avoid flooding. :wink:
I have answered your request in this thread , the blend file is included. I hope it helps. :wink:

Just for convenience :wink:

ex_savegame.zip (75.5 KB)

Remember: add a property called ‘saveable’ in the objects you want to save.


import bge
import bge # BGE core
from bge.logic import expandPath # Function to get the path to the blend file
import json # Module that allow to save in JSON (easier than in text)
from pprint import pprint # Just for debug


""" This module has the intent to show how to save all the useful data
of all objects in the scene and restore the previous state when the game
restarts.


- Use SPACEBAR to save the game.
- Use A and D to rotate the objects.
- Use R to generate new random numbers (see in debug properties).
- Restart the game to load automatically the last saved data.


Note that are restored the object's properties, positions and even the
states of them (note the direction the pads are moving, that is saved as
well).


By: Joel Gomes da Silva """


def save(cont):
    
    own = cont.owner
    scene = own.scene
    path = expandPath('//')
    
    # Sensors
    sensor = cont.sensors[0].positive # Keyboard (Spacebar)
    
    def get_attributes(obj):
        
        ### PROPERTIES ###
        # Properties names of the current object
        prop_names = obj.getPropertyNames()
        
        # Properties dictionary
        props_dict = {}
        
        # If the object has any property
        if len( prop_names ) > 0:
            
            # Iterates over the properties
            for prop in prop_names:
                
                # Fill the dictionary with the objects properties
                props_dict[prop] = obj[prop]
                
        ### ATTRIBUTES ###
        # Fill dictionary with data of current object
        obj_data = { 'position' : list( obj.worldPosition ), # Convert the vector to list first
        'orientation' : list( obj.worldOrientation.to_euler() ), # Do the same as above, but the matrix to euler first
        'state' : obj.state, 
        'instances' : {}, # If the object is a group object, it will have others as instances
        'properties' : props_dict } # And finally, the properties we got before
        
        # Return the attributes dictionary of the current object
        return obj_data
    
    #### INITIALIZE ####
    
    # When save button is pressed
    if sensor:
        
        # Data that will be saved in the file
        savedata = {}
        
        # Iterates over all the objects in the scene
        for obj in scene.objects:
            
            ### INSTANCE ###
            # Check if current object is instance of a group
            if obj.groupObject != None and obj.name != '__default__cam__' and 'saveable' in obj:
                
                # Fill dictionary with data of the current object
                obj_data = get_attributes(obj)
                
                # Check if there's not a group object in savedata yet
                if not obj.groupObject.name in savedata.keys():
                    savedata[obj.groupObject.name] = {'instances' : {}}
                    
                # Set instance data to savedata
                savedata[obj.groupObject.name]['instances'][obj.name] = obj_data
            
            ### COMMON ###
            # Check if object is not instance of a group object
            if obj.groupObject == None and obj.name != '__default__cam__' and 'saveable' in obj:
                
                # Fill dictionary with data of the current object
                obj_data = get_attributes(obj)
                
                # Add data of current object to main dictionary
                savedata[obj.name] = obj_data
        
        ### SAVE ###
        # Save in disk all the collected data in the scene
        with open( path + 'savegame.json', 'w' ) as open_file:
            
            json.dump( savedata, open_file )
            print( 'Scene data saved in file' )
            
    pass


def load(cont):
    
    own = cont.owner
    scene = own.scene
    path = expandPath('//')
    
    # Sensors
    sensor = cont.sensors[0].positive # Always
    
    #### INITIALIZE ####
    
    # When the scene starts
    if sensor:
        
        # Data that will be loaded from file
        savedata = {}
        
        try:
            
            # Try to open existing save file
            with open( path + 'savegame.json', 'r' ) as open_file:
                
                # Load data to savedata
                savedata = json.load( open_file )
                print( 'Scene data loaded from file' )
                
            # For each object in loaded data
            for obj in scene.objects:
                
                ### INSTANCE ###
                # If object is a group instance
                if obj.groupObject != None and obj.name != '__default__cam__' and 'saveable' in obj:
                    
                    # Loaded properties of the current object
                    cur_obj = savedata[ obj.groupObject.name ][ 'instances' ][ obj.name ]
                    
                    # Set object's position
                    obj.worldPosition = cur_obj[ 'position' ]
                    
                    # Set object's orientation
                    obj.worldOrientation = cur_obj[ 'orientation' ]
                    
                    # Set object's state
                    obj.state = cur_obj[ 'state' ]
                    
                    # If object has properties
                    if len( cur_obj[ 'properties' ].keys() ) > 0:
                        
                        # Iterates of current object's properties in savedata
                        for prop in cur_obj[ 'properties' ].keys():
                            
                            # Set the current property to current object
                            obj[ prop ] = cur_obj[ 'properties' ][ prop ]
                
                ### COMMON ###
                # If object is in scene
                if obj.groupObject == None and obj.name != '__default__cam__' and 'saveable' in obj:
                    
                    # Set object's position
                    obj.worldPosition = savedata[ obj.name ][ 'position' ]
                    
                     # Set object's orientation
                    obj.worldOrientation = savedata[ obj.name ][ 'orientation' ]
                    
                    # Set object's state
                    obj.state = savedata[ obj.name ][ 'state' ]
                    
                    # If object has properties
                    if len( savedata[ obj.name ][ 'properties' ].keys() ) > 0:
                        
                        # Iterates of current object's properties in savedata
                        for prop in savedata[ obj.name ][ 'properties' ].keys():
                            
                            # Set the current property to current object
                            obj[ prop ] = savedata[ obj.name ][ 'properties' ][ prop ]
                
        except FileNotFoundError:
            
            # Warning message
            print( 'Unable to load the save file' )
            
    pass

thank you but i need a simple script with few lines to save and load one specific object rotation and position.
few lines and simple as this one but with rotation:

import bgefrom bge import logic
path = logic.expandPath("//")


def save():
    cont = logic.getCurrentController()
    own = cont.owner 
    
    position = int(own.position.x)
    
    file = open(path+"sl_position.txt",'w')
    file.write(str(position))


def load():
    cont = logic.getCurrentController()
    own = cont.owner 
    
    file = open(path+"sl_position.txt",'r')
    line = file.readline()
    
    print(line)
    savedPosition = int(line)
    own.position.x = savedPosition

Attachments

sl_position.zip (73.6 KB)

You can easily save and manipulate data with Python, don’t relay in ‘number by number’ saving, try some dictionaries, the module json, literal_eval and so on, it will make your life easier.

Here’s a new file, saving only position and rotation. Remember, obj.worldOrientation is a matrix, you may use obj.worldOrientation.to_euler() to convert it to a vector representation. Convert it to a list to make it even easier to manipulate.

save_loc_rot_demo.blend (98.5 KB)


import bge
from bge.logic import expandPath
from ast import literal_eval # Converts str to literals (int, dict, etc)


""" Press WASD to move and SPACEBAR to save the game. Restart
the game to load the saved data automatically. """


def save(cont):
    
    own = cont.owner
    sensor = cont.sensors[0].positive
    path = expandPath('//') # Path to current savegame
    
    ############
    
    # If press save button
    if sensor:
        
        # Savedata dictionary
        savedata = {}
        
        # Set obj data to dictionary
        savedata[ 'position' ] = list( own.worldPosition ) # Converts vector to list
        savedata['rotation'] = list( own.worldOrientation.to_euler() ) # Converts matrix to euler, and then vector to list
        
        # Open file to save
        with open(path + 'savegame.txt', 'w') as openfile:
            
            # Save data to file
            openfile.write( str( savedata ) ) # Convert to string first
            
            # Warning message
            print( 'Data saved to file' )
            
def load(cont):
    
    own = cont.owner
    sensor = cont.sensors[0].positive
    path = expandPath('//')
    
    ############
    
    # Start automatically
    if sensor:
        
        # Try avoids unwanted exceptions
        try:
            
            # Open the savegame file
            with open(path + 'savegame.txt', 'r') as openfile:
                
                # Reads and converts the loaded data from file from str to literal
                savedata = literal_eval( openfile.read() )
                
                # Checks if theres the corresponding value before assigning it
                if 'position' in savedata.keys():
                    own.worldPosition = savedata['position'] # Set position
                    
                # Checks if theres the corresponding value before assigning it
                if 'rotation' in savedata.keys():
                    own.worldOrientation = savedata['rotation'] # Set rotation
                    
                # Warning message
                print( 'Data loaded from file' )
            
        # In case the savegame file is not present or other exception    
        except:
            
            # Warning message
            print( 'Cant load data from file' )