我有两个脚本; Localization.cs和LocalizeText.cs。我试图从LocalizeText.cs访问Localization.cs。当我访问GetLocalString()函数时,我收到一个错误。错误说:
" NullReferenceException:对象引用未设置为的实例 object Localization.GetLocalString(Int32 menuId)(at Assets / Scripts / Localization.cs:162)LocalizeText.Awake()(at 资产/脚本/ LocalizeText.cs:46)"
我使用Getcomponent<>从LocalizeText.cs访问Localization.cs。请问你能帮帮我吗。
感谢您的时间。
Localization.cs脚本:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using JsonFx.Json;
using UnityEngine.UI;
using System.IO;
using System;
public class Localization : MonoBehaviour {
public TextAsset LanguageFile;
private List<Language> _languages ;
private enum Languages
{
Turkish = 0,
English = 1,
German = 2,
French = 3,
Russian = 4,
Portuguese = 5,
Spanish = 6
}
private void Awake()
{
_languages = new List<Language>(JsonReader.Deserialize<Language[]>(LanguageFile.text));
PlayerPrefs.SetInt("Language", 0);
Debug.Log(GetLocalString(6));//it works
}
public string GetLocalString(int menuId)
{
string value = _languages[PlayerPrefs.GetInt("Language")].menu.MenuStrings[Convert.ToInt32(menuId)];
return value;
}
public class Language
{
public int LanguageId;
public Menu menu;
public Language()
{
menu = new Menu();
}
}
public class Menu
{
public List<string> MenuStrings;
public Menu()
{
MenuStrings = new List<string>();
}
}
}
LocalizaText.cs脚本:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class LocalizeText : MonoBehaviour {
private Text _text;
private Localization _localization;
public enum MenuItems
{
Start = 0,
Garage = 1,
WatchVideo = 2,
TiltControl = 3,
GamePadControl = 4,
Yes = 5,
Continue = 6,
CityRoad = 7,
SnowyRoad = 8,
Ridgeway = 9,
MainMenu = 10,
Exit = 11,
Speed = 12,
Acceleration = 13,
Brake = 14,
Play = 15,
Loading = 16,
LeaderBoard = 17,
Quests = 18,
Achivements = 19,
No = 20,
AreYouSure = 21
}
public MenuItems MenuItemStrings;
private void Awake()
{
_text = GetComponent<Text>();
_localization = GameObject.Find("Localization").GetComponent<Localization>();
Debug.Log(_localization);
Debug.Log(_localization.GetLocalString(System.Convert.ToInt32(MenuItemStrings)));
}
}
答案 0 :(得分:1)
private List<Language> _languages;
填入Awake
方法,另一个脚本也尝试使用Awake
方法访问它。那么当脚本尝试从列表中访问某种语言时,会先运行Awake
方法会发生什么?在填充列表的方法之前?
获得NullReferenceException
。
因此,尝试将访问块抛入Start
方法,如果这不起作用,那么json解析有问题,或者密钥不存在。
答案 1 :(得分:0)
我假设 LOLslowSTi 表示问题所在,Awake
中有两种方法。
您可以将其更改为Start
。或者您可以更改script execution order
。
文档:http://docs.unity3d.com/Manual/class-ScriptExecution.html