我目前正在开发一个小游戏,训练自己为Unity编写一些代码。
在此代码中,我使用了3种不同的脚本:一个用于控制游戏角色的移动,另一个用于管理玩家的统计信息,最后一个用于获得玩家生活的视觉支持。
机芯使用以下功能:
void GetNextWaypoint()
{
if(wavepointIndex >= Waypoints.points.Length - 1)
{
EndPath();
return;
}
wavepointIndex++;
target = Waypoints.points[wavepointIndex];
}
void EndPath()
{
PlayerStats.Lives--;
StartCoroutine(LivesUI.GetComponent<LivesUI>().Damage());
Destroy(gameObject);
}
EndPath启动我要使用的协程。
此协程用于LivesUI:
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class LivesUI : MonoBehaviour
{
public Text livesText;
//Not used because not optimized
// void Update() {
// livesText.text = PlayerStats.Lives.ToString() + " LIVES";
// }
public IEnumerator Damage()
{
livesText.text = PlayerStats.Lives.ToString() + " LIVES";
yield return livesText;
}
}
该信息存储在PlayerStats中:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerStats : MonoBehaviour
{
public static int Money;
public int startMoney = 400;
public static int Lives;
public int startLives= 20;
void Start()
{
Money=startMoney;
Lives= startLives;
}
}
所以我在Unity中遇到此错误:
错误CS0120:非静态字段,方法或属性
Component.GetComponent<LivesUI>()
需要对象引用
由于我想在LivesUI
中使用Lives,因此无法静态传递公共类。我可以在脚本中使用此协程吗?