无法将类型“int"隐式转换为“bool"Unity [英] Cannot implicitly convert type `int' to `bool' Unity
问题描述
我在 Unity2d 上遇到脚本问题.这是控制台日志:"Assets/Scripts/themeswitch.cs(35,19): error CS0029: 无法将类型 int' 隐式转换为
bool'";"Assets/Scripts/themeswitch.cs(39,19): error CS0029: 无法将类型 int' 隐式转换为
bool'";我试图在这个论坛中搜索一个问题,但这不是我需要的.这是脚本:
I have a problem with a script on Unity2d.
This is the console logs:
"Assets/Scripts/themeswitch.cs(35,19): error CS0029: Cannot implicitly convert type int' to
bool'"
"Assets/Scripts/themeswitch.cs(39,19): error CS0029: Cannot implicitly convert type int' to
bool'"
I've tried to search a problem in this forum, but it was not what I needed. Here is the script:
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class themeswitch : MonoBehaviour {
public GameObject lightbtn;
public GameObject darkbtn;
public GameObject lightmode;
public GameObject darkmode;
public void darktheme ()
{
darkbtn.SetActive(true);
lightbtn.SetActive(false);
lightmode.SetActive(false);
darkmode.SetActive(true);
Handheld.Vibrate();
PlayerPrefs.SetInt("Theme", 1);
}
public void lighttheme ()
{
darkbtn.SetActive(false);
lightbtn.SetActive(true);
lightmode.SetActive(true);
darkmode.SetActive(false);
Handheld.Vibrate();
PlayerPrefs.SetInt("Theme", 2);
}
void Start ()
{
if (PlayerPrefs.GetInt("Theme", 1)){
darktheme();
}
if (PlayerPrefs.GetInt("Theme", 2)){
lighttheme();
}
}
}
帮我解决这个问题,因为我是 unity 的新手!)谢谢)
Help me solve this problem, because i'm new at unity!) Thanks)
推荐答案
顾名思义 PlayerPrefs.GetInt
返回一个 int
,而不是一个 bool
.
As the name says PlayerPrefs.GetInt
returns an int
, not a bool
.
您正在使用
if(PlayerPrefs.GetInt("Theme", 1))
存在三个问题:
- 首先,它不是
bool
而是int
- 你多次使用它,这很昂贵
- 您使用它两次使用不同的默认返回值
你更想要的是读一遍
var themeIndex = PlayerPrefs.GetInt("Theme", 1);
其中 1
是 默认 值,如果没有找到带有 Theme
键的播放器首选项.
where 1
is the default value returned if there was no player prefs found with the key Theme
.
然后做任何一个
if(themeIndex == 1)
{
darktheme ();
}
else if(themeIndex == 2)
{
lighttheme();
}
else
{
// What if it is something else?
}
或者直接去switch-case
switch (themeIndex)
{
case 1:
darktheme();
break;
case 2:
lighttheme();
break;
default:
// What jf it is something else?
}
此外,在更改值后,您还应该调用保存它
Additionally after changing the value you should also save it calling
PlayerPrefs.Save();
否则这只能在 OnApplicationQuit
这篇关于无法将类型“int"隐式转换为“bool"Unity的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!