我正在做一个联合/C#的对象收集游戏。我有两个脚本控制这一点,GameController和蛋清。我的问题是,虽然我已经将默认的鸡蛋数设置为1(稍后我会使这个数字更高),但这并不反映在我的GameController的eggsLeft统计中:它开始并保持在0。收集/销毁一个鸡蛋也不会影响这个数目。我对编程非常陌生(不到一个月!)我想知道我哪里出了问题。
GameController脚本:
public class GameController : MonoBehaviour{
public int eggsLeft = 1;
public bool collectedAll = false;
void Update ()
{
if (eggsLeft <= 0)
{
collectedAll = true;
}
else collectedAll = false;
}
}蛋类脚本:
public class Eggs : MonoBehaviour
{
GameController gc;
void Start()
{
gc = GameObject.FindGameObjectWithTag("GameController").GetComponent<GameController>();
}
void OnMouseDown()
{
Destroy(gameObject);
gc.eggsLeft--;
}
}发布于 2020-11-20 02:36:06
您的解决方案不能工作的具体原因是因为和整数是一个值类型。在你的蛋类中,我们做的是gc.eggsLeft--,你得到的是蛋的值,然后减去一个.但是,您不会再次将该值重新分配给变量。
为了使事情更清楚一些,我们可以通过以下操作来增强您的代码:
public class GameController : MonoBehaviour
{
[SerializeField]
private int eggsLeft = 1;
public bool collectedAll
{
get { return eggsLeft == 0; }
}
public void CollectEgg ( )
{
if ( eggsLeft > 0 ) eggsLeft--;
}
}
public class Eggs : MonoBehaviour
{
GameController gc;
void Start ( )
{
gc = FindObjectOfType<GameController> ( );
if ( !gc ) Debug.LogError ( "Could not find a GameController!" );
}
void OnMouseDown ( )
{
Destroy ( gameObject );
gc.CollectEgg ( );
}
}现在请注意,只有在查询该属性时才会计算出collectedAll。答案是通过查看eggsLeft的值是否为零而得出的。
这意味着Egg类不需要担心GameController中正在进行的数学运算。它只是让我们GameController知道一个鸡蛋被收集,然后留在那里。
https://stackoverflow.com/questions/64922749
复制相似问题