我正在尝试使文本更改为玩家所剩手榴弹的数量。我已经尝试设置手榴弹的数量3然后开始显示手榴弹的数量是什么为文本也是那样。但我有以下错误:
Assets\Scripts\Throwgrenade.cs(20,24):错误CS0029:无法将类型“int”隐式转换为“UnityEngine.GameObject”
而且
Assets\Scripts\Throwgrenade.cs(23,10):错误CS1624:“Throwgrenade.Update()”的主体不能是迭代器块,因为“void”不是迭代器接口类型
这是我的代码:
public int amountOfGrenades = 3;
public GameObject grenadesText;
public GameObject NOgrenadesText;
void Start()
{
grenadesText = amountOfGrenades;
}
void Update()
{
if (Input.GetKeyDown("q") && amountOfGrenades >= 1)
{
ThrowingGrenade();
}
if(amountOfGrenades == 0)
{
yield return new WaitForSeconds(5.0f);
NOgrenadesText.SetActive(true); // Enable the text so it shows
yield return new WaitForSeconds(5.0f);
NOgrenadesText.SetActive(false); // Disable the text so it is hidden
}
}
>
第一个错误很容易解释。
你可能是说
grenadesText.GetComponent<Text>().text = amountOfGrenades.ToString();
..或者直接制造
public Text grenadesText;
或您正在使用的任何文本组件(例如tmp_text
)
然后不能在update
方法中使用yield
...只能在IEnumerator
方法中使用...
看起来应该有点像
public int amountOfGrenades = 3;
// Simply use the correct type right away
public Text grenadesText;
public GameObject NOgrenadesText;
private void Start()
{
grenadesText.text = amountOfGrenades.ToString();
}
private void Update()
{
// Avoid the stringed versions wherever possible
if (Input.GetKeyDown(KeyCode.Q))
{
if(amountOfGrenades > 0)
{
// I don't know what happens in here
// but whenever you are increasing or decreasing the amountOfGranades value
// you again want to call
// grenadesText.text = amountOfGrenades.ToString();
// in order to update the display
ThrowingGrenade();
}
if(amountOfGrenades == 0)
{
StopAllCoroutines ();
StartCoroutine (NoGrenadesRoutine());
}
}
}
private IEnumerator NoGrenadesRoutine ()
{
yield return new WaitForSeconds(5.0f);
NOgrenadesText.SetActive(true); // Enable the text so it shows
yield return new WaitForSeconds(5.0f);
NOgrenadesText.SetActive(false); // Disable the text so it is hidden
}