Unity C# 空引用异常 [英] Unity C# Null Reference Exception
问题描述
我正在尝试使用 C# 代码从 Unity
中的 int
变量获取数据.下面是我用来获取 int
的 C#
代码.
I am trying to get data from an int
variable in Unity
using C# code.
Below is the C#
code I am using to get the int
.
using UnityEngine;
using System.Collections;
public class endGameMessage : MonoBehaviour {
public static int score2;
void Start () {
GameObject thePlayer = GameObject.FindWithTag("Player");
gameScript game = thePlayer.GetComponent<gameScript>();
score2 = game.score;
}
// Update is called once per frame
void Update () {
Debug.Log (score2);
}
}
下面是我试图从中提取数据的另一个脚本中的代码.
Below is the code from the other script I am trying to pull the data from.
using UnityEngine;
using System.Collections;
public class gameScript : MonoBehaviour {
//score
public int score = 0;
void OnTriggerEnter(Collider other) {
if(other.gameObject.tag =="hammer"){
GameObject.FindGameObjectWithTag("pickUpMessage").guiText.text = ("Picked Up A Hammer");
Destroy(other.gameObject);
Debug.Log("collision detected hammer");
audio.PlayOneShot(gotHit);
score = score+10;
}
}
}
我可以让 int
值遇到另一个脚本,但它总是 0,即使 int
本来是 10.
I can get the the int
value to come across to the other script but its always 0 even if the int
was meant to be 10.
我的问题是如何在脚本中保持值?任何帮助表示赞赏.
My question is how would i keep the value across the scripts? Any help is appreciated.
推荐答案
你有很多可能性.
第一个是将您的 Score 设置为游戏脚本的静态参数.
这样你就可以在任何地方访问它:
So you can access it anywhere just like that :
int myScore = gameScript.Score ;
声明应该是:
And the declaration should be :
public static int score;
如果你想从不同的脚本中保存很多不同的值,第二种可能性要好得多.在这种情况下,您需要定义一个 gameContext 单例.
如果你不知道这是什么,你应该看看 C# 中的单例:[https://msdn.microsoft.com/en-us/library/ff650316.aspx]
If you don't know what is this, you should take a look at singleton in C# : [https://msdn.microsoft.com/en-us/library/ff650316.aspx]
Singleton 将允许您拥有游戏上下文的单个实例.在您的情况下,您的单身人士将有一个 Score 属性.您将能够从任何场景和任何脚本中获得价值.
Singleton will allow you to have a single instance of your gameContext. In your case, your singleton will have a Score attribute. And you will be able to get the value from any scene and any scripts.
这是目前最好的方法.
这篇关于Unity C# 空引用异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!