Unity:如何存储游戏中的一些数据并在下次运行时恢复它

时间:2016-12-10 00:04:33

标签: c# unity3d data-serialization

在我的游戏中,我有一个丰富的收藏品,如果玩家已经收集并返回场景,我希望每个收藏品都不会重生。例如,在一个场景中可能有大约一百个这样的收藏品,如果玩家收集其中一个,离开场景然后返回,他们收集的那个不会重生,但其余的都会重生。

经过一番研究后,我认为我应该使用数据序列化来存储已经收集了哪些收藏品但哪些收藏品没有,但我不确定如何去做这个,这个概念对我来说很新鲜。有人可以向我解释一下我应该做些什么吗?

由于

1 个答案:

答案 0 :(得分:1)

使用PlayerPrefs存储播放器的当前状态。

以下是选项:

  1. PlayerPrefs不支持布尔值,因此您可以使用整数(0表示false,1表示为true)并为每个收集项分配一个整数。专业人士:更容易实施。缺点:如果存储对象的数量非常高并且需要更多的工作量来进行读/写,则会占用太多内存。

  2. 将一个整数分配给多个收藏品并按位存储它们并来回转换。优点:对于大量存储对象,内存更少,读/写速度更快。 cons:将每个整数的数量限制为int32中的位数。那是32。

  3. 为所有收藏品分配一个大字符串并来回转换。优点:您可以存储除true / false以外的更多状态,也可以使用任何加密来保护数据免受黑客入侵。缺点:我无法想到。

  4. 选项1:

    //store
    PlayerPrefs.SetKey("collectible"+i, isCollected?1:0);
    
    //fetch
    isCollected = PlayerPrefs.GetKey("collectible"+i, 0) == 1;
    

    按位:

    int bits = 0;//note that collectiblesGroup1Count cannot be greater than 32
    for(int i=0; i<collectiblesGroup1Count; i++) 
        if(collectibleGroup1[i].isCollected)
           bits |= (1 << i);
    
    //store
    PlayerPrefs.SetKey("collectiblesGroup1", bits);
    
    //fetch
    bits = PlayerPrefs.GetKey("collectiblesGroup1", 0);//default value is 0
    for(int i=0; i<collectiblesGroup1Count; i++) 
        collectibleGroup1[i].isCollected = (bits && (1 << i)) != 0;
    

    字符串方法:

    string bits = "";//consists of many C's and N's each for one collectible
    for(int i=0; i<collectiblesCount; i++) 
        bits += collectibleGroup1[i].isCollected ? "C" : "N";
    
    //store
    PlayerPrefs.SetKey("collectibles", bits);
    
    //fetch
    bits = PlayerPrefs.GetKey("collectibles", "");
    for(int i=0; i<collectiblesCount; i++) 
        if(i < bits.Length)
            collectible[i].isCollected = bits[i] == "C";
        else
            collectible[i].isCollected = false;