PersistatePlayerPosition.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using System;
  2. using UnityEngine;
  3. using Valve.VR;
  4. namespace Calibration
  5. {
  6. public class PersistatePlayerPosition : MonoBehaviour
  7. {
  8. private const String KEY_PLAYER_POS_X = "player_pos_x";
  9. private const String KEY_PLAYER_POS_Y = "player_pos_y";
  10. private const String KEY_PLAYER_POS_Z = "player_pos_z";
  11. private Transform playerTransform;
  12. public SteamVR_Action_Boolean savePos;
  13. // Start is called before the first frame update
  14. void Start()
  15. {
  16. playerTransform = GetComponent<Transform>();
  17. savePos.AddOnStateDownListener(OnSavePos, SteamVR_Input_Sources.Any);
  18. Load();
  19. }
  20. private void OnSavePos(SteamVR_Action_Boolean fromaction, SteamVR_Input_Sources fromsource) => Save();
  21. void Load()
  22. {
  23. if (PlayerPrefs.HasKey(KEY_PLAYER_POS_X) && PlayerPrefs.HasKey(KEY_PLAYER_POS_Y) && PlayerPrefs.HasKey(KEY_PLAYER_POS_Z))
  24. {
  25. var x = PlayerPrefs.GetFloat(KEY_PLAYER_POS_X);
  26. var y = PlayerPrefs.GetFloat(KEY_PLAYER_POS_Y);
  27. var z = PlayerPrefs.GetFloat(KEY_PLAYER_POS_Z);
  28. playerTransform.position = new Vector3(x,y,z);
  29. }
  30. }
  31. public void Save()
  32. {
  33. var position = playerTransform.position;
  34. PlayerPrefs.SetFloat(KEY_PLAYER_POS_X, position.x);
  35. PlayerPrefs.SetFloat(KEY_PLAYER_POS_Y, position.y);
  36. PlayerPrefs.SetFloat(KEY_PLAYER_POS_Z, position.z);
  37. PlayerPrefs.Save();
  38. }
  39. }
  40. }