gpt4 book ai didi

c# - Unity C# 中的泛型

转载 作者:太空宇宙 更新时间:2023-11-03 23:33:51 27 4
gpt4 key购买 nike

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

这个例子是一个简化版本,实际上我不会使用计数 float 来定义协程的长度,但长度将基于动画和翻译。

我正在尝试做的事情是否可行?

“以某种方式使用“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"
}
}

最佳答案

解决方案是约束泛型类型,这样泛型方法就知道如何设置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;
}
}

关于c# - Unity C# 中的泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31246134/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com