Unity C#中的泛型

安德斯·潘登潘(AndersPødenphant)

我在使用泛型的语法和规则上遇到很多麻烦。我正在尝试构建一个结构,其中不同的类可以在协程运行时使用WaitAction类禁用输入,一旦协程完成,请重新启用它。

此示例是简化版本,实际上,我不会使用计数浮点数来定义协程的长度,但是该长度将基于动画和翻译。

我想尽一切可能吗?

“以某种方式使用“ T _ready”将“主类”中的“ bool ready”更改回“ true””

public class Main : Monobehaviour {

  WaitAction _waitAction = new WaitAction();

  public bool ready;
  float delay = 5f;

  void Update()
  {
    if(Input.GetMouseButton(0) && ready)
      {
          ready = false;
          StartCoroutine(_waitAction.SomeCoroutine((delay, this));
      }
  }


public class WaitAction {

    public IEnumerator SomeCoroutine<T>(float count, T _ready)
    {
        float time = Time.time;

        while(Time.time < time + count)
        {
            yield return null;
        }
        // Somehow use "T _ready" to change the "bool ready" in "Main Class" back to "true"
    }
}
大卫·阿尔诺

解决方案是限制泛型类型,以使泛型方法知道如何设置ready标志。使用接口很容易做到这一点:

public interface IReady
{
    bool ready { get; set; }
}

public class Main : Monobehaviour, IReady {

    ...
    public bool bool ready { get; set; }
    ...
}


public class WaitAction {

    public IEnumerator SomeCoroutine<T>(float count, T _ready) where T : IReady
    {
        ...
        _ready.Ready = true;
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章