Unity打包后限制运行次数

本文介绍了如何在Unity中通过C#脚本实现打包后应用运行次数的限制。具体做法是利用Windows注册表来存储和检查运行次数,当达到预设次数后自动退出应用。

特殊原因,在Unity 打包后,需要对运行的次数做一定的限制,这里用到C#的注册列表的控制来达到限制的效果

以下代码挂在Unity一个物体里就行了;如果是有切换场景的,记得需要挂在不销毁的物体上

using UnityEngine;
using System.Collections;
using Microsoft.Win32;


public class SetUseTime : MonoBehaviour {


// Use this for initialization
void Start () {
        SetPlayUseTime();
    }

// Update is called once per frame
void Update () {

}


    void SetPlayUseTime()
    {
        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("UseTime", (object)3);              //创建键值,存储可使用次数
            return;
        }
        try
        {
            object usetime = RegKey.GetValue("UseTime");        //读取键值,可使用次数
            print("还可以使用:" + usetime + "次");
            int newtime = int.Parse(usetime.ToString()) - 1;
            if (newtime < 0)
            {
                Application.Quit();
            }
            else
            {
                RegKey.SetValue("UseTime", (object)newtime);    //更新键值,可使用次数减1
            }
        }
        catch
        {
            RegKey.SetValue("UseTime", (object)3);
            print("更新使用3次");
        }
    }
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值