CoplayDev/unity-mcp · error · JsonSerializationException

Cannot deserialize Vector4 from {token.Type}: '{token}'

Error message

Cannot deserialize Vector4 from {token.Type}: '{token}'

What it means

Thrown by Vector4Converter.ReadJson when the JSON token is neither a JArray with count >= 4 nor a JObject. Vector4 accepts [x, y, z, w] array form or {"x":..,"y":..,"z":..,"w":..} object form.

Source

Thrown at MCPForUnity/Runtime/Serialization/UnityTypeConverters.cs:198

            writer.WriteStartObject();
            writer.WritePropertyName("x");
            writer.WriteValue(value.x);
            writer.WritePropertyName("y");
            writer.WriteValue(value.y);
            writer.WritePropertyName("z");
            writer.WriteValue(value.z);
            writer.WritePropertyName("w");
            writer.WriteValue(value.w);
            writer.WriteEndObject();
        }

        public override Vector4 ReadJson(JsonReader reader, Type objectType, Vector4 existingValue, bool hasExistingValue, JsonSerializer serializer)
        {
            JToken token = JToken.Load(reader);
            if (token is JArray arr && arr.Count >= 4)
                return new Vector4((float)arr[0], (float)arr[1], (float)arr[2], (float)arr[3]);
            if (token is not JObject jo)
                throw new JsonSerializationException($"Cannot deserialize Vector4 from {token.Type}: '{token}'");
            return new Vector4(
                (float)jo["x"],
                (float)jo["y"],
                (float)jo["z"],
                (float)jo["w"]
            );
        }
    }

    /// <summary>
    /// Safe converter for Matrix4x4 that only accesses raw matrix elements (m00-m33).
    /// Avoids computed properties (lossyScale, rotation, inverse) that call ValidTRS()
    /// and can crash Unity on non-TRS matrices (common in Cinemachine components).
    /// Fixes: https://github.com/CoplayDev/unity-mcp/issues/478
    /// </summary>
    public class Matrix4x4Converter : JsonConverter<Matrix4x4>
    {
        public override void WriteJson(JsonWriter writer, Matrix4x4 value, JsonSerializer serializer)

View on GitHub (pinned to c21bf496bc)

Solutions

  1. Send Vector4 as [x, y, z, w] array: "value": [1.0, 0.0, 0.0, 0.0].
  2. Or send as object: "value": {"x": 1.0, "y": 0.0, "z": 0.0, "w": 0.0}.
  3. Ensure arrays have exactly 4 numeric elements.
  4. Verify the target field actually expects a Vector4 and not a Vector3.

Example fix

// before
params = {"tangent": [1.0, 0.0, 0.0]}
// after
params = {"tangent": [1.0, 0.0, 0.0, 0.0]}
Defensive patterns

Strategy: type-guard

Validate before calling

def is_valid_vector4(val) -> bool:
    if isinstance(val, (list, tuple)) and len(val) >= 4:
        return all(isinstance(v, (int, float)) for v in val[:4])
    if isinstance(val, dict):
        return all(k in val for k in ('x', 'y', 'z', 'w'))
    return False

Type guard

function isVector4(val: unknown): val is number[] | {x:number;y:number;z:number;w:number} {
  if (Array.isArray(val) && val.length >= 4)
    return val.slice(0, 4).every(v => typeof v === 'number');
  if (val && typeof val === 'object' && 'x' in val && 'y' in val && 'z' in val && 'w' in val)
    return true;
  return false;
}

Try / catch

try
{
    var vec = serializer.Deserialize<Vector4>(reader);
}
catch (JsonSerializationException ex) when (ex.Message.Contains("Cannot deserialize Vector4"))
{
    return new ErrorResponse($"Vector4 must be [x,y,z,w] or {{x,y,z,w}}.");
}

Prevention

When it happens

Trigger: Deserializing a Vector4 field from JSON where the value is a scalar, string, or array with fewer than 4 elements. Less common than Vector3 errors since Vector4 is used for shader properties, tangents, and other specialized fields.

Common situations: Client sends a 3-element array where a 4-element Vector4 is expected; AI outputs a scalar for a vector field; type confusion between Vector3 and Vector4; shader property sent with wrong component count.

Related errors


AI-assisted analysis of CoplayDev/unity-mcp@c21bf496bc (2026-08-13). Data as JSON: /api/errors/45d9e15a976445ab. Report an issue: GitHub.