Search Unity

Need Help with Saving and Restoring Camera Position.

Discussion in 'Scripting' started by w1nterl0ng, Jun 21, 2011.

  1. w1nterl0ng

    w1nterl0ng

    Joined:
    Jan 19, 2010
    Posts:
    32
    Problem: I need to be able to store and recall the position (and direction) of a camera.

    Setup: I am using MouseOrbitZoom(MaxCamera) script to observe a 3d object. I want the user to have the ability to store the camera position and angle and continue to move around the scene. Then, at a later point, they have the ability to recall the stored camera angle and return to that position.

    Any sample code, or examples would be greatly appreciated.

    Thank you in advance, Fred
     
  2. appels

    appels

    Joined:
    Jun 25, 2010
    Posts:
    2,687
    just create a class to save the position :

    Code (csharp):
    1. public class CamPosSave {
    2.  
    3.     private static Transform mycampos;
    4.     public static Transform MyCamPos {
    5.         get { return mycampos; }
    6.         set { mycampos = value; }
    7.     }
    8. }
    to save :
    CamPosSave.MyCamPos = Camera.main.transform;
    to retrieve :
    Camera.main.transform = CamPosSave.MyCamPos;

    it's untested but should work, you don't need to attach the class to a gameobject.
     
    Last edited: Jun 21, 2011
  3. appels

    appels

    Joined:
    Jun 25, 2010
    Posts:
    2,687
    actualy you need to do the position and rotation seperated :

    Code (csharp):
    1. using UnityEngine;
    2.  
    3. public class CamPosSave {
    4.  
    5.     private static Vector3 myCamPos;
    6.     public static Vector3 MyCamPos {
    7.         get { return myCamPos; }
    8.         set { myCamPos = value; }
    9.     }
    10.  
    11.     private static Vector3 mycamrot;
    12.     public static Vector3 MyCamRot {
    13.         get { return mycamrot; }
    14.         set { mycamrot = value; }
    15.     }
    16. }
    Code (csharp):
    1.     void OnGUI ()
    2.     {
    3.         if (GUILayout.Button("Save"))
    4.         {
    5.             CamPosSave.MyCamPos = GameObject.Find("testcube").transform.position;
    6.             CamPosSave.MyCamRot = GameObject.Find("testcube").transform.eulerAngles;
    7.         }
    8.         if (GUILayout.Button("Restore"))
    9.         {
    10.             GameObject.Find("testcube").transform.position = CamPosSave.MyCamPos;
    11.             GameObject.Find("testcube").transform.eulerAngles = CamPosSave.MyCamRot;
    12.         }
    13.     }