私は奇妙な質問があります。私は他のスクリプトファイルから価値を得たいですが、実際には簡単です。しかし今回は別のケースがあります。例えば他のスクリプトファイルから値を取得する変数Unity C#
:私は、データ型の辞書でデータを保存player.cs
を持って
その後、私は最後のI
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();
}
}
、その後、辞書製品の値を設定しmargaretShop.cs
を持って
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class player : MonoBehaviour {
public Dictionary <string, Dictionary <string, int> > product;
}
別のスクリプトファイルで呼び出す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
あるI持っすでにmargaretSellScript.csで、このようなゲームオブジェクトを呼び出す:
mShop = GameObject.FindGameObjectWithTag ("MargaretShop").GetComponent<margaretShop>();
Player = GameObject.FindGameObjectWithTag ("player").GetComponent<player>();
任意のアイデア?
'mShop'が' nul'であるか、 'getValue'がエラーメッセージを投げているかを調べます。あなたは 'Debug.Log(" Quit: "+ mShop.getValue(" A "、" qty "));を' if(mShop == null){Debug.Log( "Null"); } else {Debug.Log( "Not Null");} 'それから私に知らせてください – Programmer
こんにちは@Programmer、それはNULLです。しかし、私はそれがプレハブの場合はマニュアルを設定することはできません。だからどのように? –
nullの場合、これは 'margaretShop'スクリプトが' MargaretShop' GameObjectに添付されていないことを意味します。したがって、 'margaretShop'を' MargaretShop'ゲームオブジェクトに添付してください。それがあなたの問題を解決するかどうか教えてください。 – Programmer