我有一个奇怪的问题。我想从其他脚本文件中获得价值,但实际上它很容易。但是这次我有另一个案子。从其他脚本文件变量获得价值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