- Home /
Why are the fields of my SerializedObject null when I set another field to its default value?
I am trying to learn more about how to write play mode tests in Unity3D and I am facing a peculiar behaviour in one of my tests. I am using SerializedObject
to set the values of protected fields of my ScriptableObject
class CurvedMovement
but whenever I attempt to set the _speed
field to the same value as its default (50) then the other fields, _xCurve
and _yCurve
, are null
. I've tried testing with loads of different values and even tried changing the default value in the abstract class Movement
but every time the test sets the _speed
field to exactly the same value as its default value then the curves are null. Can anyone help me understand why this happens and how can I write tests without them breaking if the default value of the Movement
class changes?
The class I am testing implements the following abstract class Movement:
public abstract class Movement : ScriptableObject, IMovement
{
[SerializeField]
[Tooltip("The speed at which the object moves.")]
protected float _speed = 50f;
public abstract void Move(Rigidbody2D rigidbody);
}
The implementation I am currently testing is this:
[CreateAssetMenu(menuName = "Movement/Curved Movement")]
public class CurvedMovement : Movement
{
[SerializeField]
[Tooltip("The curve that the unit will follow along the x-axis when moving.")]
protected AnimationCurve _xCurve;
[SerializeField]
[Tooltip("The curve that the unit will follow along the y-axis when moving.")]
protected AnimationCurve _yCurve;
public override void Move(Rigidbody2D rigidbody)
{
var movementVector = new Vector2(_xCurve.Evaluate(Time.time) * _speed, _yCurve.Evaluate(Time.time) * _speed);
rigidbody.MovePosition(rigidbody.position + movementVector * Time.fixedDeltaTime);
}
}
My test is here:
[UnityTest]
public IEnumerator CurvedMovementWithSpeedGreaterThanZeroAndNoCurveDoesNotMoveTheRigidBody()
{
var speed = 50f;
var curvedMovement = ScriptableObject.CreateInstance<CurvedMovement>();
var serializedObject = new SerializedObject(curvedMovement);
serializedObject.FindProperty("_speed").floatValue = speed;
serializedObject.FindProperty("_xCurve").animationCurveValue = new AnimationCurve();
serializedObject.FindProperty("_yCurve").animationCurveValue = new AnimationCurve();
serializedObject.ApplyModifiedProperties();
var gameObject = new GameObject();
var rigidbody2D = gameObject.AddComponent<Rigidbody2D>();
rigidbody2D.gravityScale = 0;
var initialPosition = rigidbody2D.position;
curvedMovement.Move(rigidbody2D);
yield return new WaitForFixedUpdate();
Assert.AreEqual(initialPosition.x, rigidbody2D.position.x);
Assert.AreEqual(initialPosition.y, rigidbody2D.position.y);
GameObject.Destroy(gameObject);
}