기술 자료

Development

User Acquisition

Monetization

산업 분야

Cloud Code

Open Unity Dashboard

Cloud Code

이 페이지는 선택한 언어로 제공되지 않습니다.
Cloud Code
​
​
Cloud Code 3.0.0 experimental features
  • Overview
  • Stateful Cloud Code
  • Local Cloud Code server
  • Develop Cloud Code modules in the Unity Editor
  • State serialization in Cloud Code
  • Timers in Stateful Cloud Code
  1. Cloud Code
  2. Cloud Code 3.0.0 experimental features

State serialization in Cloud Code

Understand how Stateful Cloud Code serializes module state, and how to control or customize serialization behavior.
읽는 시간 4분
최근 업데이트: 한 달 전

중요
This page describes an experimental feature that might change significantly before release. It's not recommended to use or rely on experimental features in production environments due to potential instability.
Stateful Cloud Code automatically serializes and deserializes module class state between function invocations. Serialization allows class members to persist within the configured scope without manual storage management.
Understanding serialization behavior helps you design module classes and troubleshoot state persistence issues. Non-serialized fields and properties can still keep values in memory between invocations, but this behavior isn't guaranteed. Only serialized fields and properties persist reliably. The runtime can rehydrate object state from persisted data at any time.
참고
Stateful Cloud Code requires you to reference the following NuGet package versions in your modules:
  • com.unity.services.cloudcode.apis
    v0.0.26 or later
  • com.unity.services.cloudcode.core
    v0.0.4 or later

Default serialization behavior

By default, the runtime serializes module state using the following rules:
  • The runtime includes public fields and properties in the serialization.
  • The runtime excludes private fields and properties in the serialization.
This default inclusion of public members aligns with common serialization library conventions, making it familiar to developers who know standard .NET serialization patterns.
using System;using Unity.Services.CloudCode.Core;[StateScope(Scope.Player)]public class PlayerProgress{ // Serialized: public field public int Level; // Serialized: public property public int Experience { get; set; } // Not serialized: private field private DateTime _lastCalculated; // Not serialized: private property private int CachedValue { get; set; } [CloudCodeFunction("GetProgress")] public string GetProgress() { return $"Level: {Level}, Experience: {Experience}"; }}

Serialization attributes

Use Cloud Code serialization attributes to explicitly control which members to include in the serialization.

Exclude public members from serialization

Apply
[CloudCodeIgnoreProperty]
to exclude a public field or property from serialization. Use this attribute for cached values, computed properties, or data that doesn't need to persist.
팁
Use
[CloudCodeIgnoreProperty]
for computed or cached values to keep serialized state minimal. Only persist data that needs to survive between function calls.
using System.Collections.Generic;using Unity.Services.CloudCode.Core;[StateScope(Scope.Player)]public class PlayerInventory{ public List<string> Items = new List<string>(); // Excluded from serialization despite being public [CloudCodeIgnoreProperty] public int CachedItemCount; [CloudCodeFunction("AddItem")] public void AddItem(string item) { Items.Add(item); CachedItemCount = Items.Count; // Recalculated anyway }}

Include private members in serialization

Apply
[CloudCodeSerializeProperty]
to include a private field or property in serialization. Use this attribute to persist internal state while maintaining encapsulation.
using System.Collections.Generic;using Unity.Services.CloudCode.Core;[StateScope(Scope.MultiplayerSession)]public class GameSession{ // Included in serialization despite being private [CloudCodeSerializeProperty] private List<string> _playerIds = new List<string>(); // Included in serialization despite being private [CloudCodeSerializeProperty] private string _currentTurnPlayerId; public int PlayerCount => _playerIds.Count; [CloudCodeFunction("JoinSession")] public string JoinSession(string playerId) { _playerIds.Add(playerId); if (_playerIds.Count == 1) { _currentTurnPlayerId = playerId; } return $"Player {playerId} joined. {PlayerCount} players in session."; }}

Custom serialization

For advanced scenarios, implement the
IStateSerializer
interface to control how the runtime serializes and deserializes your module state. This interface enables you to do the following:
  • Use a specific serialization library or format.
  • Handle complex types that require custom conversion logic.
  • Optimize serialization for performance or payload size.
  • Handle migration of persisted state after you deploy a new module version.
중요
If you change the structure of serialized data, ensure backward compatibility or implement migration logic using the
IStateSerializer
interface methods.

The IStateSerializer interface

The Cloud Code SDK provides the
IStateSerializer
interface. Implement this interface on your module class to replace the default serializer with your own behavior. The interface declares the following two methods:
namespace Unity.Services.CloudCode.Core{ public interface IStateSerializer { // Called to serialize the object state. byte[] OnSerialize(); // Called to deserialize and restore object state. void OnDeserialize(byte[] input); }}
팁
Test serialization independently. When using custom serializers, write unit tests to verify that your
OnSerialize
and
OnDeserialize
implementations work correctly outside the module runtime.

Custom serialization example with a third-party serializer

The following example demonstrates custom serialization using
Newtonsoft.Json
to serialize a game session's player list.
중요
Changes to serialization library behavior between module versions can change how the runtime stores and restores your state.
using System.Collections.Generic;using Newtonsoft.Json;using Newtonsoft.Json.Linq;using Unity.Services.CloudCode.Core;[StateScope(Scope.MultiplayerSession)]public class GameSession : IStateSerializer{ public List<string> _playerIds = new List<string>(); public string _hostPlayerId; public byte[] OnSerialize() { var json = JsonConvert.SerializeObject(this); return System.Text.Encoding.UTF8.GetBytes(json); } public void OnDeserialize(byte[] data) { var json = System.Text.Encoding.UTF8.GetString(data); var serializer = JsonSerializer.Create(); serializer.Populate(JObject.Parse(json).CreateReader(), this); } [CloudCodeFunction("AddPlayer")] public string AddPlayer(string playerId) { if (_playerIds.Count == 0) { _hostPlayerId = playerId; } _playerIds.Add(playerId); return $"Player {playerId} joined. Host: {_hostPlayerId}"; } [CloudCodeFunction("GetPlayers")] public List<string> GetPlayers() { return _playerIds; }}

Copyright © 2026 Unity Technologies
법률 정보개인정보 처리방침쿠키Documentation Terms of Use개인 정보 판매 또는 공유 금지개인정보 보호 선택(쿠키 설정)

'Unity', Unity 로고 및 기타 Unity 상표는 미국 및 기타 지역 내 Unity Technologies 또는 그 계열사의 상표 또는 등록상표입니다(자세한 내용은 여기에서 확인하세요). 기타 명칭 또는 브랜드는 해당 소유자의 상표입니다.

일부 페이지는 편의를 위해 기계 번역되었으며 부정확한 내용이 있을 수 있습니다. 정보가 상충되는 경우, 영어 버전을 우선으로 참조하세요.

  • 보고 있는 페이지
    • Default serialization behavior

    • Serialization attributes

      • Exclude public members from serialization

      • Include private members in serialization

    • Custom serialization

      • The IStateSerializer interface

      • Custom serialization example with a third-party serializer


이 페이지의 문제 보고
​
​