Serializing Vector3 in Unity

2014-07-08 07:24:06

In Unity Vector3 is not marked as serializable.
So, if you try to serialize a class of our own containing a property of type Vector3 you will get the following error:

SerializationException: Type UnityEngine.Vector3 is not marked as Serializable.

To make this work, one way is to make a converter class based on the Vector3 type, which is really simple and fast to do, so...

Let's go!

You probably have your class definition like so:

[Serializable()]
public class MyClass {
	public Vector3 someVector3Info { get; set; }
	public MyClass() { }
}

We need to create our new converter class now:

[Serializable()]
public class WB_Vector3 {

	private float x;
	private float y;
	private float z;

	public WB_Vector3() { }
	public WB_Vector3(Vector3 vec3) {
		this.x = vec3.x;
		this.y = vec3.y;
		this.z = vec3.z;
	}

	public static implicit operator WB_Vector3(Vector3 vec3) {
		return new WB_Vector3(vec3);
	}
	public static explicit operator Vector3(WB_Vector3 wb_vec3) {
		return new Vector3(wb_vec3.x, wb_vec3.y, wb_vec3.z);
	}
}

Ok, what happened here?
First, we have our properties marked as private because we won't need to access them directly. Then we have our basic constructor, followed by a custom constructor that may come in handy at some point.
And finally we have some operator definitions that will allow us to cast from Vector3 type to our converter class and vice versa.

Now update your class property to actually save the values of the new converter class instead of the Vector3 directly.

[Serializable()]
public class MyClass {
	private WB_Vector3 _someVector3Info; 
	public Vector3 someVector3Info { 
		get {
			if (_someVector3Info == null) {
				return Vector3.zero;
			} else {
				return (Vector3)_someVector3Info;
			}
		} 
		set {
			_someVector3Info = (WB_Vector3)value;
		}
	}
	public MyClass() {}
}

Notice that we have not changed the return type of the "someVector3Info" property, so all your implementations in other places will keep working without any change. Of course if you need some other implementation in case "_someVector3Info" is null, go ahead and change that part. If you want to return null, don't forget to mark the return type nullable.

That's it! Happy coding :)

Playstation 3 Controller Mapping in Unity 3D

2014-04-13 21:56:46

I found myself a few times in need of the mapping of the PS3 Controller in Unity. Searching on the net I didn't find much, so I made a quick overview myself.
Use it like "joystick x", where x is the number of the input you want.
PS3 Controller Mapping