gpt4 book ai didi

c# - Unity C# 空引用异常

转载 作者:太空宇宙 更新时间:2023-11-03 11:09:39 24 4
gpt4 key购买 nike

我正在尝试使用 C# 代码从 Unity 中的 int 变量获取数据。下面是我用来获取 intC# 代码。

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);

}
}

下面是我试图从中提取数据的其他脚本的代码。

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。

我的问题是如何在脚本中保留值?任何帮助表示赞赏。

最佳答案

试试这个

public static int score2
{
get
{
return GameObject.FindWithTag("Player").GetComponent<gameScript>().score;
}
}

关于c# - Unity C# 空引用异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14549465/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com