Im trying to save my characters position and load it back in when coming from a new level. heres the scenario:
level1: character walks around, clicks on a button and it loads level2: level 2 consists of a 360 panorama (so the player doesn’t exist here). when i exit level 2 and return to level1 id like the character to be set in the position it was last in.
Easiest way is to use playerprefs.
Change the positition to a string, and then save that string in playerprefs.
I modified some metods I used for something else, I have not tested if it work(and I made it fast), so it might need some tweaking, but take a look at this.
//This function will save position
public void SavePos()
{
StringBuilder playerPos = new StringBuilder();
//Run through the list and make a semicolon seperated list of positions.
playerPos.Append(pos.x).Append(" ").Append(pos.y).Append(" ").Append(pos.z);
savedString = playerPos.ToString();
PlayerPrefs.SetString(SceneManager.GetActiveScene().name + "playerPosition", savedString);
Debug.Log("We saved the run: " + savedString);
}
//This function will load the saved string from a player pref and load it into a list.
public Transform LoadRun()//string posList)
{
savedString = PlayerPrefs.GetString(SceneManager.GetActiveScene().name + "playerPosition");
string[] values = savedString.Split(' ');
Transform returnTransform = new Vector3(values[0],values[1],values[2]);
return returnTransform;
Thanks @Tabu i should have mentioned im a total noob at scripting and still learning…ive never had to deal with strings yet so ill have a hunt online in the documentation to see if i can make sense of what you’ve written lol.
what i was trying to get working (in a test scene) was using playerprefs but in this form:
using UnityEngine;
using System.Collections;
public class trigger : MonoBehaviour {
void Start()
{
load();
}
void OnTriggerEnter (Collider col)
{
if (col.gameObject.tag == "trigger")
{
Application.LoadLevel("lvl2");
save();
Debug.Log("loading level");
}
}
public void Back()
{
Application.LoadLevel("lvl1");
load();
Debug.Log("loading level and previous position");
}
void load()
{
if (PlayerPrefs.GetFloat("x") != null)
{
transform.position = new Vector3(PlayerPrefs.GetFloat("x"), PlayerPrefs.GetFloat("y"), PlayerPrefs.GetFloat("z"));
save();
}
}
void save()
{
PlayerPrefs.SetFloat("x", transform.position.x);
PlayerPrefs.SetFloat("y", transform.position.y);
PlayerPrefs.SetFloat("z", transform.position.z);
}
}
in this test scene it has issues due to it re-spawning me in the trigger over and over again. am i able to spawn in a different location? what do you think?