SerializableVector3
The SerializableVector3 class is designed to make the Vector3 structure serializable in Unity's Inspector, which by default doesn't support serializing Vector3 directly when used as a private field in custom classes.
This class converts a Vector3 into three separate float values (x, y, and z), making it easy to serialize while still maintaining all the benefits of working with Vector3 in code.
Serialization
Unity's serialization system doesn't directly support
Vector3unless it is public or marked with[SerializeField]. This class offers an alternative by breaking aVector3into three individualfloatfields that can be easily serialized.
Usage
You can use this class to store a
Vector3in a custom class and still have it serialized for saving and loading
Fields
x: The x-component of the vector.
y: The y-component of the vector.
z: The z-component of the vector.
Methods | DataPersistenceManager.cs
SerializableVector3(Vector3 vector)
Converts a
Vector3into the correspondingSerializableVector3representation.
vector: Vector3 to deconstruct into 3 floats.
ToVector3()
Converts the
SerializableVector3back into aVector3.
Coding Example
// Creating a SerializableVector3 from a Vector3
SerializableVector3 serializableVector = new SerializableVector3(new Vector3(1, 2, 3));
// You can access the components individually if needed
float xComponent = serializableVector.x;
float yComponent = serializableVector.y;
float zComponent = serializableVector.z;
// Convert back to a Vector3
Vector3 originalVector = serializableVector.ToVector3();
Last updated