JensHendar.com

Saving game… please don’t turn off your browser.

This is going to be a short post (I think) about saving data in Unity3D.

Been working on a save-mechanism for the game. Turns out I should’ve started implementing it in conjunction with the inventory system, since I had to change some stuff, but I think it’s coming along pretty well. It saves the position of items if they’ve moved from their initial one, it saves the inventory and it saves the player position.

The inventory saves every thing something new is added or discarded. The new position of items save when the item is still after being discarded. And the position of the player saves in a OnApplicationQuit()-function. There is also a save button in the menu, but I haven’t decided wether or not to keep it yet. It all depens on how much autmatic saving I can do when I get more features added.

I’m saving the data in the PlayerPrefs, but since you can only save a float, int or string, I’m saving the player position like this:

 

[code lang=”js”]
PlayerPrefs.SetFloat("player_position_x", transform.position.x);
PlayerPrefs.SetFloat("player_position_y", transform.position.y);
PlayerPrefs.SetFloat("player_position_z", transform.position.z);

PlayerPrefs.SetFloat("player_rotation_x", transform.rotation.x);
PlayerPrefs.SetFloat("player_rotation_y", transform.rotation.y);
PlayerPrefs.SetFloat("player_rotation_z", transform.rotation.z);
PlayerPrefs.Save();
[/code]

And then when the game starts, I set the player position like this:

[code lang=”js”]
transform.localPosition = Vector3(PlayerPrefs.GetFloat("player_position_x"), PlayerPrefs.GetFloat("player_position_y"), PlayerPrefs.GetFloat("player_position_z"));
[/code]

The code for the item position is basically the same, but with a unique id for each item. It works for now, but it seems a little too good to be true. If it’s still working in a week I’ll write something up about it. The code for the inventory-saving is too messy to explain here, maybe when I’ve cleaned it up a bit.

Next in line is adding some “objectives” to the environment. I have something in mind, but I’ll let that be my secret until I know I can make it work.

Have a good one!

Next Post

Previous Post

© 2024 JensHendar.com

Theme by Anders Norén