如何解决静态变量在Unity中不显示
好的,首先,请原谅我的英语。好吧,我仍然使用[Serializable()]进行 SAVEFILE ,这没有问题,问题是,当我尝试使用以下方法更改此静态字符串时,用户名,在其他使用de InputField的脚本中找不到该变量的引用。没什么奇怪的, SAVEFILE 脚本只是说:
并保存脚本:
public static UIsettings uisettings;
//Data to save.
public string AirlineName = "Unknow";
public string UserName = "Unknow";
//Autoload.
public bool StartupLoad;
void Awake()
{
if(uisettings == null)
{
uisettings = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
void Start()
{
if (StartupLoad)
{
Load();
}
}
//Guardar
public void Save() //Start the SAVEGAME code
后来,我从InputFields的其他两个脚本中更改了航空公司名称和用户名的值,这两种方法如下:
public void SubmitName(string newAirlineName)
{
if(newAirlineName == "")
{
print("Write a valid name");
}
else
{
print(newAirlineName + " es valido.");
profileData.AirlineName = newAirlineName;
profileData.Save();
Debug.Log(UIsettings.uisettings.AirlineName);
}
}
如果我这样称呼它,就可以了,但是由于改变场景时这些都是无用的,因为这些值再次变为Default,所以我在以下值中使用 static :
{
public static string AirlineName = "Unknow";
}
没有钥匙,非常令人讨厌。但是,当我执行此操作时,第二个脚本的方法无法显示分配的变量,请说:错误CS0176:成员'UIsettings.AirlineName'无法使用实例引用进行访问;用类型名称代替它 ...
我有几天尝试自己解决这个问题,但是我不知道该怎么办。
我知道 SAVEGAME 脚本是一个DontDestoyOnLoad文件,就像在第一个脚本中可以看到的那样,但是我这样做不是因为没有静态。
解决方法
当您有一个静态变量(public static string AirlineName
)时,只能使用类名来引用它-而不是该类的实例-因为只有一个AirlineName
存在,并且与您班上的任何实例。
这是一个为什么出现错误的示例:
// This example shows why are you getting the error. Skip to the second example
// to see the solution that you should use
public class UiSettings : MonoBehaviour
{
public static string AirlineName = "Unknow";
}
// ...
public void SubmitName(string newAirlineName)
{
// Just an example of getting the current instance of UiSettings
UiSettings profileData = (UiSettings)GameObject.FindObjectOfType(typeof(UiSettings));
// You can't do this because AirlineName is a static property,so you can't use an
// instance variable (profileData) to access it because AirlineName doesn't belong
// to an instance
profileData.AirlineName = newAirlineName;
// You would have to access it like this
UiSettings.AirlineName = newAirlineName;
}
但是由于您通过使用UiSettings
使DontDestroyOnLoad
成为单例类,因此您可以这样做
public class UiSettings : MonoBehaviour
{
public static UIsettings uisettings;
// Do not make these static
public string AirlineName = "Unknow";
public string UserName = "Unknow";
void Awake()
{
if(uisettings == null)
{
uisettings = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
}
// ...
public void SubmitName(string newAirlineName)
{
// uisettings contains an instance of UiSettings,so you are allowed to say
// UiSettings.uisettings.AirlineName = ...
UiSettings.uisettings.AirlineName = newAirlineName;
}
我还建议将名称uisettings
更改为Instance
,以使该属性明确引用该类的单例实例。像这样:
public class UiSettings : MonoBehaviour
{
// Instead of public static UiSettings uisettings
public static UiSettings Instance { get; private set; }
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。