我有一个奇怪的问题。我想从其他脚本文件中获取价值,但实际上它很容易。但这次我还有另一个案例。
例如:
我有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> ();
任何想法?
答案 0 :(得分:1)
但是我看到它被吸引了。只是我没有激活它直到我按下 按钮。
这就是问题所在。该组件必须为enabled
,GetComponent<Script> ()
才能找到它。 {/ 1}}默认情况下来自编辑器。游戏开始时会获得Enable
然后reference
。
disable
如果您有任何代码在mShop = GameObject.FindGameObjectWithTag("MargaretShop").GetComponent<margaretShop>();
mShop.enabled = false; //disable it
脚本的Start()
函数中运行,则可以删除它们并将它们放在名为margaretShop
的自定义公共函数中。
现在,当您按下initScript()
时,可以使用Button
激活它,然后调用mShop.enabled = false;
函数在initScript()
脚本中初始化变量。那就是它。