Easy way to write and read some Transform to a text file in Unity3d?

后端 未结 2 1042
忘了有多久
忘了有多久 2021-01-22 21:53

This is strictly in Unity3D, I have an array of 100 Transform,

I want to write those to a file on the PC desktop, and later read them.

Consider ...<

2条回答
  •  独厮守ぢ
    2021-01-22 22:45

    You can use Binary Serialization.

    Create following structs:

    [Serializable]
    public struct SerializebleVector
    {
        public float x, y, z, w;
    
        public SerializebleVector(float x, float y, float z, float w = 0f)
        {
            this.x = x;
            this.y = y;
            this.z = z;
            this.w = w;
        }
    
        public static explicit operator SerializebleVector(Quaternion a)
        {
            return new SerializebleVector(a.x, a.y, a.z, a.w);
        }
    
        public static implicit operator SerializebleVector(Vector3 a)
        {
            return new SerializebleVector(a.x, a.y, a.z);
        }
    
    }
    
    [Serializable]
    public struct SerializebleTransform
    {
        SerializebleVector position;
        SerializebleVector rotation;
        SerializebleVector scale;
    
        public SerializebleTransform(Transform tr)
        {
            position = tr.position;
            rotation = (SerializebleVector) tr.rotation;
            scale = tr.lossyScale;
        }
    
    
        public static implicit operator SerializebleTransform(Transform tr)
        {
            return new SerializebleTransform(tr);
        }
    }
    

    Save method:

    public static void Save(Transform[] ts )
    {
        var data = new List();
    
        foreach (var t in ts)
        {
            data.Add(t);
        }
    
        BinaryFormatter bf = new BinaryFormatter();
        using (FileStream file = File.Create (Application.persistentDataPath + "/savedTransforms.dat"))
        {
            bf.Serialize(file, data);
        }
    }
    

    Load Method:

    public static void Load(out List ts) 
    {
        if(File.Exists(Application.persistentDataPath + "/savedTransforms.dat"))
        {
            BinaryFormatter bf = new BinaryFormatter();
            using (FileStream file = File.Open(Application.persistentDataPath + "/savedTransforms.dat", FileMode.Open))
            {
                var data = (List)bf.Deserialize(file);
                return data;
            }
        }
        else
            ts = null;
    }
    

    PS: As far as I know you can't create Transform without GameObject, so read data from SerializebleTransform into Transform kind of manually.

提交回复
热议问题