Advertisement
Guest User

Unity simple object position/rotation recorder

a guest
Apr 16th, 2021
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.56 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. // this script will record the position and rotation of the
  6. // GameObject it is placed on, and when disabled (OnDisable()),
  7. // it will write it to a CSV file of your choosing.
  8. // @kurtdekker
  9.  
  10. public class RollABallRecorder : MonoBehaviour
  11. {
  12.     public string Filename;
  13.  
  14.     void Reset()
  15.     {
  16.         Filename = System.String.Format( "Position_Rotation_" + name + ".csv");
  17.     }
  18.  
  19.     List<string> dataBuffer;
  20.  
  21.     int frameno;
  22.  
  23.     void Update ()
  24.     {
  25.         if (dataBuffer == null)
  26.         {
  27.             dataBuffer = new List<string>();
  28.         }
  29.  
  30.         // grab
  31.         var pos = transform.position;
  32.         var rot = transform.rotation;
  33.  
  34.         // format the line
  35.         string data = frameno.ToString() + ",";
  36.  
  37.         data += System.String.Format( "{0},{1},{2},", pos.x, pos.y, pos.z);
  38.  
  39.         // WARNING: These are NOT eulerAngles; these are the actual internal
  40.         // quaternion values so you can reconstruct the rotation. You can also
  41.         // store the rotation eulerAngles but they are subject to gimbal lock.
  42.         data += System.String.Format( "{0},{1},{2},{3}", rot.x, rot.y, rot.z, rot.w);
  43.  
  44.         // store
  45.         dataBuffer.Add( data);
  46.  
  47.         // next!
  48.         frameno++; 
  49.     }
  50.  
  51.     // beware of when this is called. It may suit your needs to be much
  52.     // more explicit in order to avoid overwriting the previous run's data.
  53.     // Here is some timing diagram help:
  54.     // https://docs.unity3d.com/Manual/ExecutionOrder.html
  55.  
  56.     void OnDisable()
  57.     {
  58.         if (dataBuffer != null)
  59.         {
  60.             System.IO.File.WriteAllLines( Filename, dataBuffer.ToArray());
  61.             dataBuffer = null;
  62.         }
  63.     }
  64. }
  65.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement