正确使用多个协程的方法 [英] Correct way to use multiple coroutines
问题描述
我只是觉得有一个更好的方法.我有一个需要调整大小然后压缩的纹理.这两个函数都需要一点处理时间,因此我需要将每个函数放在协程中.我得到的方式是先调整大小然后进行压缩,但是事情似乎很快就变得混乱了.推荐的构造多个顺序协程以依次触发并将处理后的变量(在这种情况下为Texture2D)从一个传递到另一个的方法是什么?
I just feel like there's a better way to this. I've got a texture that I'm needing to resize, and then compress. Both of these functions need a bit of processing time so I'm needing to put each in a coroutine. The way I've got it is I'm resizing first and then compressing but things seem like they're quickly getting messy. What is the recommended way to structure a number of sequenced coroutines to fire one after the other and pass the processed variable (in this case a Texture2D) from one to the next?
[Client]
public void PrepareServerData(Texture2D texToSend, string typeToSend)
{
StartCoroutine(DoGetTexToBytes(texToSend));
playerObj.texWidth = texToSend.width;
playerObj.texHeight = texToSend.height;
playerObj.texFormat = texToSend.format;
playerObj.tranX = tran.x;
playerObj.tranY = tran.y;
playerObj.tranZ = tran.z;
playerObj.type = typeToSend;
Player_ID id = GetComponent<Player_ID>();
playerObj.id = id.MakeUniqueIdentity();
playerObj.strength = strengthToSend;
playerObj.hitpoints = hitPointsToSend;
Network_Serializer serialize = GetComponent<Network_Serializer>();
// Send Data from Client to Server as many small sequenced packets
byte[] bytes = serialize.ObjectToByteArray(playerObj);
StartCoroutine(Network_Transmitter.instance.DoSendBytes(0, bytes));
}
IEnumerator DoGetTexToBytes(Texture2D tex)
{
DoResizeTex(tex);
byte[] texBytes = tex.GetRawTextureData(); // convert texture to raw bytes
byte[] compressedTexBytes = lzip.compressBuffer(texBytes, 9); // compress texture byte array
playerObj.texBytes = compressedTexBytes; // set compressed bytes to player object
yield return new WaitForEndOfFrame();
GameObject infoDisplayText = GameObject.Find("InfoDisplay");
infoDisplayText.GetComponent<Text>().text += "Bytes to send : " + playerObj.texBytes.Length + "\n";
}
IEnumerator DoResizeTex(Texture2D tex)
{
tex.ResizePro(1280, 1024);
tex.Apply();
yield return new WaitForEndOfFrame();
}
推荐答案
向协程添加回调过程.
private IEnumerator MyCoroutine(Action callback){
yield return null;
if (callback !=null){callback();}
}
用法:
void Start(){
StartCoroutine(MyCoroutine(()=>
{
StartCoroutine(OtherCoroutine());
}
}
如果需要使用Action,还可以从协程返回值.
You can also return values from your coroutine if needed with Action.
private IEnumerator MyCoroutine(Action<Texture2D> callback){
yield return null;
Texture2D tex = GetTexture();
if (callback !=null){callback(tex);}
}
void Start(){
StartCoroutine(MyCoroutine((texParam)=>
{
StartCoroutine(OtherCoroutine(texParam));
}
}
IEnumerator OtherCoroutine(Texture2D texture){
yield return null;
texture.DoSomething();
}
这篇关于正确使用多个协程的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!