c# - 无法在 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); }
}
解决方案
这里的主要问题:
你必须LastShownIntTimefloat
在你的script2 中重置!
否则,您只需继续用新值覆盖它,进一步减少值并将其写回PlayerPrefs
→ 下次您的script1轮询该值时,它不会重置但已被script2覆盖!
一般来说:你不应该PlayerPrefs
为了让两个组件通信而使用!
在您的情况下,我什至不会分离逻辑并费心实现它们之间的通信,而是将它们合并为一个组件。
然后没有必要读取和写入PlayerPrefs
每一帧,而只需要在某些检查点上,如
- 读一次_
Start
- 写入一次_
OnApplicationQuit
- 写入一次(适用于
OnDestroy
您切换场景但不退出应用程序的情况) - 每次您的用户丢失(被调用)时写一次
showInterstitial
- 显示广告后重置值时写入一次
我也将直接使用float
andGetFloat
而SetFloat
不是将其从 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();
}
}
推荐阅读
- apache-nifi - HandleHTTPRequest 处理器在 nifi 中创建重复的输出流文件
- windows - 在 Windows 上设置 Dockerised 命令行应用程序
- javascript - 为什么 update() 会完全覆盖我在 Firebase 中的数据?设置()与更新()
- android - Android Studio 未构建项目
- css - 如何在wordpress中的图标下方添加文本
- python - 饼图中的间距字符串
- javascript - 我正在使用 Here maps api 设置地图,但无法删除地图侦听器
- node.js - 一个域上的多个应用程序
- ios - 更改特定时间的颜色按钮,然后转到正常颜色 SWIFT
- android - 在没有过渡效果的情况下更改活动