首页 > 解决方案 > 无法在 unity3d 中重置特定的 playerprefs

问题描述

我制作了 2 个代码来管理我的插页式广告,让广告在玩家输球时每 5 分钟显示一次,但问题是我试图在玩家经过 5 分钟时重置它们并在他输球时按下按钮但它没有t 工作那么当玩家按下按钮时如何重置计时器?

这是第一个代码:

public int LastShownIntTime = 300;



void Start()
{
    #if UNITY_ANDROID
    Advertisement.Initialize(androidID);
     #endif
}
public void Update()
{

    LastShownIntTime = PlayerPrefs.GetInt("LastShownIntTime");

}     
public void showInterstitial()
{
    if (LastShownIntTime <=0)
    {
        showInterstitialwith5mint();
    }
}

public void showInterstitialwith5mint()
{
    Advertisement.Show("video");
    PlayerPrefs.SetInt("LastShownIntTime", 300);
}

第二个:

public float LastShownIntTimefloat;
 public int LastShownIntTime = 300;

void Start()
{
    LastShownIntTime = PlayerPrefs.GetInt("LastShownIntTime");
    LastShownIntTimefloat = LastShownIntTime;

}
public void Update()
{

    LastShownIntTimefloat -= Time.deltaTime;
    LastShownIntTime = (int)LastShownIntTimefloat;
    PlayerPrefs.SetInt("LastShownIntTime", LastShownIntTime);

}

}

标签: c#visual-studiounity3dtimer3d

解决方案


这里的主要问题:

你必须LastShownIntTimefloat在你的script2 中重置!

否则,您只需继续用新值覆盖它,进一步减少值并将其写回PlayerPrefs

→ 下次您的script1轮询该值时,它不会重置但已被script2覆盖!


一般来说:你不应该PlayerPrefs为了让两个组件通信而使用!

在您的情况下,我什至不会分离逻辑并费心实现它们之间的通信,而是将它们合并为一个组件。

然后没有必要读取和写入PlayerPrefs 每一帧,而只需要在某些检查点上,如

  • 一次_Start
  • 写入一次_OnApplicationQuit
  • 写入一次(适用于OnDestroy您切换场景但不退出应用程序的情况)
  • 每次您的用户丢失(被调用)时写一次showInterstitial
  • 显示广告后重置值时写入一次

我也将直接使用floatandGetFloatSetFloat不是将其从 and 转换为int.

public class MergedClass : MonoBehaviour
{
    // Rather sue a FLOAT for time!
    public float LastShownTime = 300;

    void Start()
    {
#if UNITY_ANDROID
        Advertisement.Initialize(androidID);
#endif

        // use 300 as default value if no PlayerPrefs found
        LastShownTime = PlayerPrefs.GetFloat("LastShownTime", 300f);
    }

    public void Update()
    {
        if(LastShownTime > 0f) LastShownTime -= Time.deltaTime;
    }     

    public void showInterstitial()
    {
        PlayerPrefs.SetFloat("LastShownTime", LastShownTime);
        PlayerPrefs.Save();

        if (LastShownTime <= 0f)
        {
            showInterstitialwith5mint();
        }
    }
    
    public void showInterstitialwith5mint()
    {
#if UNITY_ANDROID
        Advertisement.Show("video");
#else

        LastShownTime = 300f;
        PlayerPrefs.SetFloat("LastShownTime", LastShownTime); 
        PlayerPrefs.Save();
    }

    private void OnApplicationQuit()
    {
        PlayerPrefs.SetFloat("LastShownTime", LastShownTime);
        PlayerPrefs.Save();
    }

    private void OnDestroy()
    {
        PlayerPrefs.SetFloat("LastShownTime", LastShownTime);
        PlayerPrefs.Save();
    }
}

推荐阅读