Sha*_*ail -1 c# unity-game-engine
我有以下(相关)代码:
public class GameController : MonoBehaviour {
public class Timer
{
int elapsedTime;
int pausedTime;
bool isCounting;
public void Start()
{
int startTime = DateTime.Now.Millisecond;
while(isCounting)
{
elapsedTime = DateTime.Now.Millisecond - startTime;
}
}
}
private void Update()
{
//Debug logging of the timer functions
if(startButton.CompareTag("Clicked"))
{
Timer.Start();
}
}
Run Code Online (Sandbox Code Playgroud)
}
此代码生成以下错误:非静态字段,方法或属性'GameController.Timer.Start()`需要对象引用.我怎样才能解决这个问题?
(注意:对于几乎每种情况,此错误的原因都不同,因此很难将其称为重复.)
在Update()你打电话Timer.Start();.这是对类的静态方法的调用Timer.此静态方法不存在,因此您会收到错误.使方法静态是没有选择的,因为它使用非静态成员elapsedTime.解决问题的方法是获得一个Timer实例并调用该方法:
public class Timer
{
int elapsedTime;
int pausedTime;
bool isCounting;
public void Start()
{
int startTime = DateTime.Now.Millisecond;
while(isCounting)
{
elapsedTime = DateTime.Now.Millisecond - startTime;
}
}
}
public class GameController : MonoBehaviour
{
// The new member
Timer timer = new Timer();
private void Update()
{
//Debug logging of the timer functions
if(startButton.CompareTag("Clicked"))
{
this.timer.Start();
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
62 次 |
| 最近记录: |