for some reason, this script doesn’t work, it Logs the messages, but it dosn’t actually load… it saves. Is there something I’m not doing? it works when i say PlayerPrefsX… in the script i’m referencing this one to, but I just want to reference this one instad of typing “PlayerPrefsX…”
Any and all help would be appreciated!
using UnityEngine;
using System.Collections;
public class Game : MonoBehaviour {
public static void Save(string lv, Vector3 v, Quaternion q) {
Debug.Log("Saving position: "+v+" and rotation: "+q+" for "+lv);
PlayerPrefsX.SetVector3(lv+"position",v);
PlayerPrefsX.SetQuaternion(lv+"rotation",q);
}
public static void Load(string lv, Vector3 v, Quaternion q) {
Debug.Log("Loading info for "+lv);
v = PlayerPrefsX.GetVector3(lv+"position");
q = PlayerPrefsX.GetQuaternion(lv+"rotation",q);
}
}
here’s a way to use Save();
Game.Save("Level 1", transform.position, transform.rotation);
and Game.Load(); is set up the same way, but for some reason doesn’t even work besides Debug.log();
That won't work since Vector3 and Quaternion are value types, not reference types and additionally Transform.position and .rotation are properties.
Change your methods to
public static void Load(string lv, Transform obj)
{
PlayerPrefsX.SetVector3(lv+"position",obj.position);
PlayerPrefsX.SetQuaternion(lv+"rotation",obj.rotation);
}
public static void Load(string lv, Transform obj)
{
obj.position = PlayerPrefsX.GetVector3(lv+"position");
obj.rotation = PlayerPrefsX.GetQuaternion(lv+"rotation",q);
}
That will work because Transform is a class and therefore a reference type.
edit:
In the case that you want to save an arbitrary Vector3 and Quaternion you have to use the `ref` or `out` keyword and use temp variables when calling the load function:
public static void Load(string lv, out Vector3 v, out Quaternion q)
{
v = PlayerPrefsX.GetVector3(lv+"position");
q = PlayerPrefsX.GetQuaternion(lv+"rotation",Quaternion.identity);
}
Vector3 tmpPosition;
Quaternion tmpRotation;
Game.Load("Level 1",out tmpPosition, out tmpRotation);
// use the two variables
When using out the variables don't have to be initialized when passing to the function but you can't read them inside your function until you assigned them.
When using ref the variables have to be initialized and can be read inside the function. They just act as a reference type.