简体   繁体   English

Unity C中的泛型#

[英]Generics in Unity C#

I am having a lot of trouble with the syntax and the rules for using Generics. 我在使用泛型的语法和规则方面遇到了很多麻烦。 I am trying to make a structure, where different classes, can use the WaitAction class to disable input while a couroutine is running, an re-enable it once the coroutine is finished. 我正在尝试创建一个结构,其中不同的类可以使用WaitAction类在couroutine运行时禁用输入,一旦协程完成就重新启用它。

This example is a simplified version, and in reality I will not be using a count float to define the length of the coroutine, but the length will based on animations and translation. 这个例子是一个简化版本,实际上我不会使用count float来定义协程的长度,但是长度将基于动画和翻译。

Is what I am trying to do at all possible? 我想尽力做什么?

"Somehow use "T _ready" to change the "bool ready" in "Main Class" back to "true"" “不知何故用”T _ready“将”Main Class“中的”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"
    }
}

The solution is to constrain the generic type, such that the generic method knows how to set the ready flag. 解决方案是约束泛型类型,以便泛型方法知道如何设置ready标志。 This is easily done using an interface: 使用界面可以轻松完成:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM