Unity C#:尝试呼叫班级时出错' Update()

时间:2017-07-18 09:54:59

标签: c# unity3d

我有以下(相关)代码:

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();
    }

}

}

此代码生成以下错误:非静态字段,方法或属性' GameController.Timer.Start()`需要对象引用。我该如何解决这个问题?

(注意:此错误的原因几乎在所有情况下都不同,因此很难将其称为重复。)

2 个答案:

答案 0 :(得分:5)

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();
        }    
    }    
}

答案 1 :(得分:-2)

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();
        }    
    }
}

这个问题有两种选择

  1. 你的make方法是静态的:

    public static void Start()
    {
        int startTime = DateTime.Now.Millisecond;
    
        while(isCounting)
        {
            elapsedTime = DateTime.Now.Millisecond - startTime;
        }
    }
    
  2. 您可以通过创建对象类计时器来访问start方法:

    Timer obj= new Timer()
    obj.Start();