unity游戏引擎- Unity3D:尝试在c#中自定义睡眠/等待功能

本文关键字:自定义 功能 等待 引擎 游戏 Unity3D unity | 更新日期: 2023-09-27 17:49:35

这一切都是从昨天开始的,当我使用这段代码来创建一个片段:

void Start() {
    print("Starting " + Time.time);
    StartCoroutine(WaitAndPrint(2.0F));
    print("Before WaitAndPrint Finishes " + Time.time);
}
IEnumerator WaitAndPrint(float waitTime) {
    yield return new WaitForSeconds(waitTime);
    print("WaitAndPrint " + Time.time);
}

从:http://docs.unity3d.com/Documentation/ScriptReference/MonoBehaviour.StartCoroutine.html

问题是我想从该类中设置一个静态变量:

class example
{
    private static int _var;
    public static int Variable
    {
        get { return _var; }
        set { _var = value; }
    }
}

问题是什么?问题是,如果把这个变量放在函数的参数中,这个"临时参数"将在函数结束时被销毁……我搜索了一下,我记得:

class OutExample
{
    static void Method(out int i)
    {
        i = 44;
    }
    static void Main()
    {
        int value;
        Method(out value);
        // value is now 44
    }
}

从:http://msdn.microsoft.com/es-es/library/ms228503.aspx

但是,(总是有一个"但是"),迭代器不能有ref out…所以我决定创建自己的等待函数,因为Unity没有Sleep函数…

这就是我的代码:
    Debug.Log("Showing text with 1 second of delay.");
    float time = Time.time;
    while(true) {
        if(t < 1) {
            t += Time.deltaTime;
        } else {
            break;
        }
    }
    Debug.Log("Text showed with "+(Time.time-time).ToString()+" seconds of delay.");

代码有什么问题?问题是,这是非常野蛮的代码,因为它可以产生内存泄漏,漏洞,当然,应用程序的延迟…

那么,你建议我怎么做?

unity游戏引擎- Unity3D:尝试在c#中自定义睡眠/等待功能

你可以这样做:

void Start()
{
    print( "Starting " + Time.time );
    StartCoroutine( WaitPrintAndSetValue( 2.0F, theNewValue => example.Variable = theNewValue ) );
    print( "Before WaitAndPrint Finishes " + Time.time );
}
/// <summary>Wait for the specified delay, then set some integer value to 42</summary>
IEnumerator WaitPrintAndSetValue( float waitTime, Action<int> setTheNewValue )
{
    yield return new WaitForSeconds( waitTime );
    print( "WaitAndPrint " + Time.time );
    int newValueToSet = 42;
    setTheNewValue( newValueToSet );
}

如果在你的延迟之后你需要读取和更新一个值,你可以例如传递Func<int> readTheOldValue, Action<int> setTheNewValue并调用以下lambdas () => example.Variable, theNewValue => example.Variable = theNewValue

下面是更一般的例子:

void Delay( float waitTime, Action act )
{
    StartCoroutine( DelayImpl( waitTime, act ) );
}
IEnumerator DelayImpl( float waitTime, Action act )
{
    yield return new WaitForSeconds( waitTime );
    act();
}
void Example()
{
    Delay( 2, () => {
        print( "After the 2 seconds delay" );
        // Update or get anything here, however you want.
    } );
}

这是你想要的吗?

Thread.Sleep(time)

你在这里寻找什么可以完成使用Task.Delay:

void Start()
{
    print("Starting " + Time.time);
    WaitAndPrint(2.0F);
    print("Before WaitAndPrint Finishes " + Time.time);
}
Task WaitAndPrint(float waitTime)
{
    Task.Delay(TimeSpan.FromSeconds(waitTime))
        .ContinueWith(t => print("WaitAndPrint " + Time.time));
}

然后你可以传递lambdas/delegate,可能关闭变量,在你的程序中移动数据。