PersistatePlayerPosition.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using Valve.VR;
  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. }