【時間限制】修改Start()函數裏的minTime和maxTime時間即可。限制時間也可精確到秒,比如:
DateTime minTime = Convert.ToDateTime("2019-4-23 12:22:05");
【次數限制】SetPlayUseNumber()爲限制次數方法,修改鍵值名就可以重新計算("UseTime")
本腳本是限制時間和次數的搭配使用,可自行修改。
using Microsoft.Win32;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class SetUserTime : MonoBehaviour {
int userNum = 0;
public Button Btn_expire;
// Use this for initialization
void Start () {
//===(比如3月1日開始計算,到4月1日結束)
//小於minTime 時間或者大於maxTime時間 ,將不可使用
DateTime minTime = Convert.ToDateTime("2019-3-1");
DateTime maxTime = Convert.ToDateTime("2019-4-1");
if (minTime > DateTime.Now || DateTime.Now > maxTime)
{
userNum = 4;
}
SetPlayUseNumber();
//if (minTime < DateTime.Now && DateTime.Now < maxTime)
//{
// //===用於限時功能
// //在這段時間內能使用xx功能
//}
}
/// <summary>
/// 設置用戶使用次數
/// </summary>
void SetPlayUseNumber()
{
RegistryKey RootKey, RegKey;
//項名爲:HKEY_CURRENT_USER\Software
RootKey = Registry.CurrentUser.OpenSubKey("SOFTWARE", true);
//打開子項:HKEY_CURRENT_USER\Software\MyRegDataApp
if ((RegKey = RootKey.OpenSubKey("TestToControlUseTime", true)) == null)
{
RootKey.CreateSubKey("TestToControlUseTime"); //不存在,則創建子項
RegKey = RootKey.OpenSubKey("TestToControlUseTime", true);
RegKey.SetValue("UseTime7", (object)3); //創建鍵值,存儲可使用次數
return;
}
try
{
object usetime = RegKey.GetValue("UseTime7"); //讀取鍵值,可使用次數
print("還可以使用:" + usetime + "次");
//int newtime = int.Parse(usetime.ToString()) - 1;
int newtime = int.Parse(usetime.ToString()) - userNum;
if (newtime < 0)
{
//到期退出程序
RegKey.SetValue("UseTime7", (object)newtime);
Btn_expire.gameObject.SetActive(true);
Invoke("OnExit", 2);//延時退出,可在退出前顯示提示消息
}
else
{
RegKey.SetValue("UseTime7", (object)newtime); //更新鍵值,可使用次數減1
}
}
catch
{
RegKey.SetValue("UseTime7", (object)3);
print("更新使用3次");
}
}
private void OnExit()
{
Application.Quit();
}
}