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
值传递给其他脚本,但是即使int
本来是10,它也始终为0.
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设置为gameScript的静态参数.
-
因此您可以在任何地方访问它,就像这样:
So you can access it anywhere just like that :
int myScore = gameScript.Score ;
并且声明应为:
And the declaration should be :
public static int score;
如果您要从differents脚本中保存大量的differents值,则第二种可能性要好得多. 在这种情况下,您需要定义一个gameContext单例.
The second possibilities is far better if you want to save a lot of differents values from differents script. In this case, you need to define a gameContext singleton.
如果您不知道这是什么,则应该看一下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将允许您拥有一个gameContext实例. 在您的情况下,您的单身人士将具有得分"属性. 您将能够从任何场景和任何脚本中获取价值.
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.
这是迄今为止最好的方法.
This is the best way so far.
这篇关于Unity C#空引用异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!