我有一個奇怪的問題。我想從其他腳本文件中獲得價值,但實際上它很容易。但是這次我有另一個案子。從其他腳本文件變量獲得價值Unity C#
例如:
我有player.cs
是保存數據和數據類型的字典
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class player : MonoBehaviour {
public Dictionary <string, Dictionary <string, int> > product;
}
那麼我margaretShop.cs
是集字典產品的價值
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
using System.Linq;
public class margaretShop : MonoBehaviour {
player Player;
// Use this for initialization
void Start() {
Player = GameObject.FindGameObjectWithTag ("player").GetComponent<player>();
setValue("A", "id", "10");
setValue("A", "name", "A");
setValue("A", "qty", "4");
setValue("A", "price", "120");
}
// Update is called once per frame
void Update() {
}
void init() {
if (Player.product != null) {
return;
}
Player.product = new Dictionary<string, Dictionary <string, int> >();
}
public int getValue(string nameproduct, string property) {
init();
if (Player.product.ContainsKey (nameproduct) == false) {
return 0;
}
if (Player.product [nameproduct].ContainsKey (property) == false) {
return 0;
}
return Player.product [nameproduct] [property];
}
public void setValue(string nameproduct, string property, int value) {
init();
if (Player.product.ContainsKey (nameproduct) == false) {
Player.product[nameproduct] = new Dictionary<string, int>();
}
Player.product [nameproduct] [property] = value; // This store to player.cs file product
}
public string[] getProductName() {
return Player.product.Keys.ToArray();
}
}
,然後最後我用另一個腳本文件稱之爲margaretSellScript.cs
using UnityEngine;
using System.Collections;
using System.Linq;
using UnityEngine.UI;
public class margaretSellScript : MonoBehaviour {
margaretShop mShop;
player Player;
// Use this for initialization
void Start() {
mShop = GameObject.FindGameObjectWithTag ("MargaretShop").GetComponent<margaretShop>();
Player = GameObject.FindGameObjectWithTag ("player").GetComponent<player>();
Debug.Log("QTY : " + mShop.getValue ("A", "qty"));
}
}
在此腳本中:Debug.Log("QTY : " + mShop.getValue ("A", "qty"));
爲什麼我無法從player.cs產品變量字典中獲取值?該值必須是「4」對不對?
誤差爲Object reference not set to an instance of an object
我已經這樣調用遊戲對象在margaretSellScript.cs:
mShop = GameObject.FindGameObjectWithTag ("MargaretShop").GetComponent<margaretShop>();
Player = GameObject.FindGameObjectWithTag ("player").GetComponent<player>();
任何想法?
找出'mShop'是'nul'還是'getValue'正在拋出錯誤信息。你可以通過替換'Debug.Log(「QTY:」+ mShop.getValue(「A」,「qty」));'if(mShop == null){Debug.Log(「Null」); } else {Debug.Log(「Not Null」);}'然後讓我知道 – Programmer
嗨@Programmer,它是NULL。但是如果它是預製的,我不能設置手動。又怎樣 ? –
如果它爲null,那麼這意味着'margaretShop'腳本沒有附加到'MargaretShop'遊戲對象。所以將'margaretShop'附加到'MargaretShop'遊戲對象。讓我知道如果這可以解決您的問題。 – Programmer