c# - Unity c#使用其他脚本中的变量不起作用
问题描述
我尝试编写一个小游戏。我的问题:我有一个跳转计数器,它的名字是什么。我想在面板中显示这个数量的跳跃,如果我与“目标”发生碰撞,就会出现。但是,如果我发生碰撞,并且面板出现,则只有: Jumps required: 0 并且我得到以下错误代码:
NullReferenceException:对象引用未设置为对象 GameScript.Start () 的实例(在 Assets/Scripts/GameScript.cs:28)
最大的问题是,变量不在另一个脚本中,jumpcounter 自己工作正常
我做了 YouTube 上很多视频所说的,所以检查我是否真的将 UI 文本附加到我的公共文本,但我没有看到任何视频具有真正有用的答案......
private void Start()
{
counter = Player.GetComponent<PlayerController>().jumpCounter;
}
private void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.name == "Hand")
{
LevelFinishedPanel.SetActive(true);
Player.GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezeAll;
if (counter <= maxJumpsForGold)
{
ShowUpJumpCounter.text = "Jumps you needed: " + counter.ToString();
Gold.enabled = true;
}
else if (counter <= maxJumpsForSilver && counter > maxJumpsForGold)
{
ShowUpJumpCounter.text = "Jumps you needed: " + counter.ToString();
Silver.enabled = true;
}
else if (counter <= maxJumpsForBronze && counter > maxJumpsForSilver)
{
ShowUpJumpCounter.text = "Jumps you needed: " + counter.ToString();
Bronze.enabled = true;
}
else
{
ShowUpJumpCounter.text = "Jumps you needed: " + counter.ToString();
}
我希望显示我的跳跃量,但实际上它只是 0。
解决方案
您counter
在 Start() 处设置变量,但在其他脚本中更新变量时它不会更新。发生这种情况是因为即使您在 Start() 将其设置为 player 上的 jumpCounter 的值,它也不会“绑定”到该值。您实际上只是创建另一个具有 jumpCounter 值的变量。请尝试以下操作:
private void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.name == "Hand")
{
counter = Player.GetComponent<PlayerController>().jumpCounter;
LevelFinishedPanel.SetActive(true);
Player.GetComponent<Rigidbody2D>().constraints =
RigidbodyConstraints2D.FreezeAll;
if(counter <= maxJumpsForGold)
{
ShowUpJumpCounter.text = "Jumps you needed: " + counter.ToString();
Gold.enabled = true;
}
else if (counter <= maxJumpsForSilver && counter > maxJumpsForGold)
{
ShowUpJumpCounter.text = "Jumps you needed: " + counter.ToString();
Silver.enabled = true;
}
else if (counter <= maxJumpsForBronze && counter> maxJumpsForSilver)
{
ShowUpJumpCounter.text = "Jumps you needed: " + counter.ToString();
Bronze.enabled = true;
}
else
{
ShowUpJumpCounter.text = "Jumps you needed: " + counter.ToString();
}
}
}
在这里,不是在 Start() 处设置它,而是在发生碰撞时设置变量。
推荐阅读
- jquery - 使用codeigniter上传多张图片时如何修复图片的宽度和高度?
- python - JMeter中的模块导入错误
- reactjs - 警告:validateDOMNesting(...): 不能作为子级出现
我正在尝试使用 reactjs 进行这种工作。但它返回错误
<table> cannot appear as a child of <tr>
这是我的 RoomRow.js
import React from 'react' import {Link} from 'r
- python - 如何在数据框列中的字符之后删除字符串的其余部分?
- excel - 工作簿名称更改,如何在 VBA 中更改/调整它?
- r - 在 R 中交换错位的单元格?
- api - YouTube Api V3:未配置访问权限
- c# - 如何使用正则表达式在一个组中获得 2 个字段?
- ionic3 - 如何在 Ionic 3 中使用社交分享?
- javascript - URL 中的特殊字符