我需要将一个场景的脚本中的变量发送到另一个场景的脚本。我一直得到“NullReferenceException:对象引用未设置为对象的实例”。我做错了什么?
public class FirstScript : MonoBehaviour {
private int x = 1;
OtherScript other;
void Start () {
other= GetComponent<OtherScript>();
}
private void AddToOther(){//is called when a button is pressed
print ("AddToOther");
other.ShowInt(x);//this is the offending line?
}
//-------------------
public class OtherScript : MonoBehaviour {
public int y;
public void ShowInt(int a){
y = a;
print ("y " + y);
}
// ------------- EDITED PART
public class FirstScript : MonoBehaviour {
private int x = 1;
OtherScript other;
void Start () {
}
private void AddToOther(){//is called when a button is pressed
print ("AddToOther");
other = gameObject.AddComponent<OtherScript>();
other.ShowInt(x);
}
感谢您的链接,我试图寻找类似的问题,但找不到那个:)