Can't use GameObject inside .continuewith

Hi,

I’m trying to print my GameObject inside a .continuewith like this:

but it’s not printing my GameObject.

I checked my Scope Access with an Integer variable and it’s working.

Does anyone know why I can’t use my Unity GameObject inside .ContinueWith?


You can’t use unity objects outside of the main thread. Task.Delay runs on a new thread.
A continuation by default will run on the same thread as the Task it’s continuing I think.
You actually have to explicitly tell it to run on a different thread context for it to do so.
You can tell it to run on the Main unity thread, and that would fix the error.

//Schedule to run on the thread it's being declared in (main thread)
.ContinueWith(...{...}, TaskScheduler.FromCurrentSynchronizationContext());

I wouldn’t use a Task.Delay just for a delay though. You’re starting a thread to wait some time. Plenty of easier and cheaper ways to delay execution, like using a coroutine, or polling a timer.

Perhaps your actual threaded code does more than wait, perhaps it calculates and returns a value, and this is just a simplified version of the problem for our benefit

In that case, I would use async await, not a continuation. Async await deals with thread context switching automatically, and makes your code look synchronous.
You await a Task (possibly fetching the result from that task if it has a return type), and the code that you need to run afterwards can be put right underneath it, like normal synchronous code.

public async void AsyncBomb(GameObject Player)
{
  ...
  await Task.Delay(new TimeSpan(0,0,3-BombSpeed));
  print(a);
}
5 Likes

Awesome! nice explanation. Thanks.