Unity C#中从Realm(MongoDB)获取并遍历游戏关卡数据
问题
我是一名正在学习Unity游戏开发的PHP开发者,对相关技术还比较陌生。我已搭建好Realm实例用于存储玩家关卡数据(LevelStats),目前数据存储功能正常,但不清楚如何获取LevelStats中的所有数据行并进行遍历。
我的Realm实体类代码如下:
using Realms; public class LevelStats : RealmObject { [PrimaryKey] public string Level { get; set; } public RealmInteger<int> Score { get; set; } public LevelStats() { } public LevelStats(string Level, int Score) { this.Level = Level; this.Score = Score; } }
在应用启动时我添加了测试关卡数据:
public class LevelScore : MonoBehaviour { private Realm _realm; private LevelStats _levelStats; void Start() { _realm = Realm.GetInstance(); _realm.Write(() => { _levelStats = _realm.Add(new LevelStats("1", 100)); _levelStats = _realm.Add(new LevelStats("2", 2000)); _levelStats = _realm.Add(new LevelStats("3", 1500)); _levelStats = _realm.Add(new LevelStats("4", 5000)); }); if (_levelStats is null) // if null create blank table { Debug.Log("created row"); _realm.Write(() => { _levelStats = _realm.Add(new LevelStats("1", 0)); }); } Debug.Log("created row"); } }
现在在关卡界面的脚本中,我尝试获取所有关卡数据,但不知道如何编写遍历逻辑:
// Start is called before the first frame update void Start() { _realm = Realm.GetInstance(); var theLevelData = _realm.All<LevelStats>(); ///// I want to code a loop here for all the rows /// foreach() or while() loop or something like that but cant figure it out Debug.Log("Level: " + level + "Score: " + Score); // Debug.Log(levels.Level); }
解决方案
1. 遍历所有LevelStats数据
Realm的_realm.All<LevelStats>()返回的是可枚举集合,直接用foreach循环遍历即可,代码示例:
// Start is called before the first frame update void Start() { _realm = Realm.GetInstance(); var allLevelStats = _realm.All<LevelStats>(); // 遍历每一行关卡数据 foreach (var levelStat in allLevelStats) { Debug.Log($"Level: {levelStat.Level} Score: {levelStat.Score}"); } }
2. 优化初始化代码的冗余问题
你当前的初始化代码每次启动都会重复添加相同主键的数据,Realm会自动忽略重复主键的添加操作,但可以改成仅在无数据时初始化,避免不必要的操作:
public class LevelScore : MonoBehaviour { private Realm _realm; void Start() { _realm = Realm.GetInstance(); // 检查是否已有关卡数据,没有再执行初始化 if (!_realm.All<LevelStats>().Any()) { _realm.Write(() => { _realm.Add(new LevelStats("1", 100)); _realm.Add(new LevelStats("2", 2000)); _realm.Add(new LevelStats("3", 1500)); _realm.Add(new LevelStats("4", 5000)); }); Debug.Log("初始化关卡数据完成"); } else { Debug.Log("已有关卡数据,无需重复初始化"); } } }
3. 关键注意点
- 访问Realm数据时,确保当前线程是Realm允许的线程(Unity主线程默认支持)
- 修改数据必须包裹在
_realm.Write()代码块中 RealmInteger<int>可直接当作普通int使用,输出时会自动转换为数值
内容的提问来源于stack exchange,提问作者Barry Connolly
相关产品推荐
相关产品推荐

