Menu
CoddyTech

JsonUtility

جزء من قسم هندسة الألعاب في Unity في رحلة Unity على Coddy. الدرس 30 من 64.

JSON هو نص يحتوي على قيم كائن، لذا يمكن تسجيله أو إرساله أو كتابته في ملف. يحوّل JsonUtility.ToJson(obj) كائنًا إلى JSON، وينشئ JsonUtility.FromJson<T>(json) كائنًا جديدًا من النوع T. يتبع JsonUtility القواعد نفسها التي يتبعها Inspector، لذا يعمل مع فئة [System.Serializable]:

[System.Serializable]
public class PlayerProfile
{
    public string playerName = "Ana";
    public int level = 7;
    public List<string> badges = new List<string> { "Explorer", "Sharpshooter" };
    [SerializeField] private float hoursPlayed = 12.5f;
    private int secretCode = 1234;
    public int Rank { get; set; } = 3;
}
string json = JsonUtility.ToJson(new PlayerProfile());
// {"playerName":"Ana","level":7,"badges":["Explorer","Sharpshooter"],"hoursPlayed":12.5}
PlayerProfile copy = JsonUtility.FromJson<PlayerProfile>(json);

لا يظهر كل من secretCode وRank. يكتب JsonUtility الحقول العامة والحقول الخاصة المحددة بـ [SerializeField]، ولا يكتب أي شيء آخر: فلا يكتب الخصائص، ولا الحقول الثابتة، ولا الحقول الخاصة العادية. كما يتجاهل حقل Dictionary، وكذلك الحقل الذي فئته ليست [System.Serializable]. وهذه أيضًا الحقول التي يستثنيها Inspector. تكتب JsonUtility.ToJson(obj, true) بيانات JSON نفسها موزعة على عدة أسطر، لتكون أسهل قراءة.

تُكتب القائمة الموجودة داخل فئة، كما هي الحال مع badges. أما القائمة وحدها فلا تُكتب: يحتاج JsonUtility إلى كائن في المستوى الأعلى، لذا فإن JsonUtility.ToJson(scores) لقائمة List<int> التي تحتوي على 10 و20 و30 تُرجع {}. ضع القائمة داخل فئة وحوّلها؛ فعندئذٍ تُكتب قائمة ScoreBoard التي تحتوي على القائمة نفسها على النحو التالي: {"scores":[10,20,30]}:

[System.Serializable]
public class ScoreBoard
{
    public List<int> scores;
}
challenge icon

التحدي

متوسط

شارك الفريق على هيئة شيفرة JSON.

  1. في CharacterBuild، اجعل Strength حقلًا، public int strength;، وعلّم agility باستخدام [SerializeField].
  2. أسفله، اكتب صنفًا [System.Serializable] باسم Team يحتوي على public List<CharacterBuild> heroes;. في TeamCode، اجعل القائمة public Team team; وسجّل شيفرة JSON الخاصة بها.
  3. يقرأ LoadCode القيمة code إلى team ويسجّل Loaded 3 heroes.

اضغط على «العب» ثم اضغط على مفتاح المسافة: سيظهر الفريق بصيغة JSON. ثم اضغط على «تحقق».

جرّب بنفسك

using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class CharacterBuild
{
    public string hero;
    public int Strength { get; set; }
    private int agility;
}

جميع دروس هندسة الألعاب في Unity

تدرّب بنفسك: Playground لـ Unity