I would like to pass a 2D Texture to a coroutine, make some changes, then return it back to the source function. Is this possible or do I need something else?
EDIT: This code is from a map creation system on game startup so it has about 10 seconds to do it’s thing, during a loading screen with a progress bar. I’m creating a water flow system and the idea is to spawn coroutines where it pools (based on height) and write pixels into the
Texture2D rivers = new Texture2D(512, 512, TextureFormat.RGBA32, false);
Color32 riverPixelsArray = rivers.GetPixels32();
for (int i = 0; i < riverPixelsArray.Length; ++i)
riverPixelsArray *= black;*
IEnumerator Spawn(Texture2D rivers)
rivers.SetPixel(10, 10, white);
rivers.Apply(); // <— trying to avoid this
yield return rivers; // <— is this right?
Several points about the use of Coroutines in general:
First, a Coroutine is started via
StartCoroutine(YourCoroutineHere()). StartCoroutine() can be called by any object that inherits from MonoBehaviour.
yield return part of the Coroutine is when and how long you want to pause execution of the Coroutine.
yield return null means that Unity will wait until the next frame to resume the Coroutine, while
yield return new WaitForSeconds(1) will tell Unity to pause the Coroutine for 1 second (while leaving the rest of the game unaffected). A Coroutine can have any number of
yield return statements anywhere, and the function doesn’t even have to end with a
yield return. This is the only function of the
yield return statement in a Coroutine; you cannot pass any information outside of the function in this manner.
Finally, passing information from a function call to the parent function can be generally accomplished by passing in function parameters by reference:
private void MyFuction(ref GameObject myObject), or by defining out parameters in your function:
private void MyFuction(out GameObject myObject). Any defined changes to the local variable
myObject will be reflected in any objects that you pass into the function when you actually call it. However, doing this with Coroutines is highly discouraged. This is because Coroutines are executed asynchronously, meaning that the parent function could have/probably has already moved on to the statement after the Coroutine call before the Coroutine itself completes execution
In your situation, I would recommend first making sure that you need to use a Coroutine at all. Coroutines are generally reserved for operations that either take too long to complete in one frame (like loading a scene) or time-dependent operations that need to be executed in parallel with the rest of the game (like animating objects via code). If you are absolutely sure you need to use a Coroutine, I would not try to pass an information to the source function, and instead either take care of whatever needs to be done in the Coroutine itself or have the Coroutine call a separate function at the end.