在Unity / Vuforia中保存已查看元素的集合

时间:2017-07-05 18:03:36

标签: c# unity3d vuforia

我有寻找9种不同元素的寻宝游戏。只有4个具有特殊的标记'。当您查看特定元素时,屏幕底部会显示一个标记,显示为已收集。问题是,我无法弄清楚如何使用playerprefs保存这个,这样你就可以收集所有4个令牌,即使你关闭了游戏。这是令牌脚本

using UnityEngine;

使用Vuforia; 使用System.Collections;

public class token_icon:MonoBehaviour,ITrackableEventHandler {

private TrackableBehaviour mTrackableBehaviour;

public GameObject token;
public GameObject lime_token;
public GameObject loconut_token;
public GameObject crown_token;
public GameObject gin_token;

void Start()
{
    mTrackableBehaviour = GetComponent<TrackableBehaviour>();
    if (mTrackableBehaviour)
    {
        mTrackableBehaviour.RegisterTrackableEventHandler(this);
    }
}

public void OnTrackableStateChanged(
                                TrackableBehaviour.Status previousStatus,
                                TrackableBehaviour.Status newStatus)
{
    if (newStatus == TrackableBehaviour.Status.DETECTED ||
        newStatus == TrackableBehaviour.Status.TRACKED)
    {
        token.SetActive(true);
    }
    else
    {
        token.SetActive(false);
    }
}

}

1 个答案:

答案 0 :(得分:0)

PlayerPrefs课程仅保存并加载intfloatstring类型的数据。要保存每个标记的状态,可以将本地newStatus枚举转换为int,并将其用作PlayerPrefs保存的值。此外,您应该创建新功能以保存和加载PlayerPrefs。加载时只需将PlayerPrefs.GetInt("Key")转换回TrackableBehaviour.Status枚举。以下是PlayerPrefs文档的链接,以防您尚未看到它:https://docs.unity3d.com/ScriptReference/PlayerPrefs.html

我通过添加两个新功能来修改您的源代码,以展示如何开始。

public class token_icon:MonoBehaviour,ITrackableEventHandler {

private TrackableBehaviour mTrackableBehaviour;

public GameObject token;
public GameObject lime_token;
public GameObject loconut_token;
public GameObject crown_token;
public GameObject gin_token;

void Start()
{
    //Inserted Function
    LoadStatus();

    mTrackableBehaviour = GetComponent<TrackableBehaviour>();
    if (mTrackableBehaviour)
    {
        mTrackableBehaviour.RegisterTrackableEventHandler(this);
    }
}

public void OnTrackableStateChanged(
                                TrackableBehaviour.Status previousStatus,
                                TrackableBehaviour.Status newStatus)
{
    if (newStatus == TrackableBehaviour.Status.DETECTED ||
        newStatus == TrackableBehaviour.Status.TRACKED)
    {
        token.SetActive(true);
    }
    else
    {
        token.SetActive(false);
    }
    //Inserted Function
    SaveStatus();
}

//Save to PlayerPrefs
private void SaveStatus()
{
    PlayerPrefs.SetInt("Token", (int)newStatus);
    PlayerPrefs.Save();
}

//Load from PlayerPrefs
private void LoadStatus()
{
    if (PlayerPrefs.HasKey("Token"))
    {
        TrackableBehaviour.Status loadStatus = (TrackableBehaviour.Status)PlayerPrefs.GetInt("Token");

        if (loadStatus == TrackableBehaviour.Status.DETECTED ||
            loadStatus == TrackableBehaviour.Status.TRACKED)
        {
            token.SetActive(true);
        }
        else
        {
            token.SetActive(false);
        }
    }
}

}

显然,这可以用更一般的方式编写,不仅仅用于单个令牌游戏对象,但我对你的工作流程知之甚少,无法猜测最佳方法。