이상한 질문이 있습니다. 다른 스크립트 파일에서 가치를 얻고 싶지만 실제로는 쉽습니다. 그러나 이번에는 다른 경우가 있습니다. 예를 들어다른 스크립트 파일 변수에서 값 가져 오기 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
안녕하세요 @ 프로그래머, 그것은 NULL입니다. 하지만 조립식이라면 수동으로 설정할 수는 없습니다. 그래서 방법 ? –
null 인 경우, 이것은'margaretShop' 스크립트가'MargaretShop' GameObject에 첨부되어 있지 않다는 것을 의미합니다. 그래서'margaretShop'을'MargaretShop' GameObject에 붙이십시오. 문제가 해결되면 알려주십시오. – Programmer