我想做拖放游戏。游戏可以运行和玩,但有一些错误。基于下面的2种编码,有一个错误:-
全编码:-
Vector3 startposition;
getTarget.transform.position = Vector3.Lerp(getTarget.transform.position, startposition, 1.0f);
startposition = getTarget.GetComponent<Drag>().originalPosition;1)第80行错误编码
startposition = getTarget.GetComponent<Drag>().originalPosition;全编码:-
if ((dropobject.name == namepartial+"Target") && (getTarget.name == namepartial))
{
startTime = Time.time;
journeyLength = Vector3.Distance(getTarget.transform.position, dropobject.transform.position);
correct = true;
correctdone = false;
if (dropobject.name == "ToasterTarget")
{
infoPanel1.SetActive(true);
infoPanel2.SetActive(false);
infoPanel3.SetActive(false);
infoPanel4.SetActive(false);
infoPanel5.SetActive(false);
infoPanel6.SetActive(false);
infoPanel7.SetActive(false);
}
}
if ((dropobject.name == namepartial+"Target") && (getTarget.name == namepartial))
{
playAudioCorrect();
target.GetComponentInChildren<Renderer>().enabled = false;
getTarget.tag = "Untagged";
int tempscore = int.Parse(scoretext.GetComponent<Text>().text) + 50;
scoretext.GetComponent<Text>().text = tempscore.ToString();
int tempscore1 = int.Parse(finalScoreText.GetComponent<Text>().text) + 50;
finalScoreText.GetComponent<Text>().text = tempscore1.ToString();
}2)第150行的错误编码:-
if ((dropobject.name == namepartial+"Target") && (getTarget.name == namepartial))来自控制台的第80和105行错误:-
NullReferenceException:对象引用未设置为对象Drag.Update ()的实例(位于资产/GameApaNi/脚本/Drag.cs:105)
发布于 2019-06-17 04:08:17
您没有显示实际得到的错误,但是根据您的代码,我只能假设您得到了两个错误
NullReferenceException
第一个意思是,要么没有设置getTarget (null) --因为否则就会在前面的行中得到错误--要么getTarget.GetComponent<Drag>()返回null,这意味着getTarget上没有组件Drag。
如果它没有确切地附加到getTarget对象,您可以使用GetComponentInParent()在层次结构上递归地搜索它,或者使用GetComponentInChildren(true)向下在层次结构中递归地搜索它。
第二个基本相同:没有设置dropobject或getTarget,所以没有设置null。
对于这两种情况,您都应该检查检查器引用,设置断点,并逐行设置代码调试。
一些进一步的建议:
通常,为什么要使用完全相同的if条件?
if ((dropobject.name == namepartial+"Target") && (getTarget.name == namepartial))是分开电话的两倍?你不能把这两个街区合并成一个吗?
另外,尽量避免重复调用GetComponent,只存储结果一次,并重复使用引用。
var scoreText = scoretext.GetComponent<Text>();
int tempscore = int.Parse(scoreText.text) + 50;
scoreText.text = tempscore.ToString();如果可能的话,甚至不要使用它,而是在Awake中只获得一次相应的组件,并在应用程序的整个运行时重用相同的引用。
如果您在字段中引用这些内容,例如通过Unified监察员引用,如
public GameObject scoretext;然后将类型更改为
public Text scoretext;而且您可以完全摆脱所有的GetComponent调用,这将使您的脚本更高效(快速)。
https://stackoverflow.com/questions/56623902
复制相似问题