Search Unity

Can't use GameObject inside .continuewith

Discussion in 'Scripting' started by MoeinZavar, Jul 2, 2022.

  1. MoeinZavar

    MoeinZavar

    Joined:
    Mar 14, 2021
    Posts:
    4
    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?
     

    Attached Files:

  2. Hikiko66

    Hikiko66

    Joined:
    May 5, 2013
    Posts:
    1,304
    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.

    Code (CSharp):
    1.  
    2. //Schedule to run on the thread it's being declared in (main thread)
    3. .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.

    Code (CSharp):
    1. public async void AsyncBomb(GameObject Player)
    2. {
    3.   ...
    4.   await Task.Delay(new TimeSpan(0,0,3-BombSpeed));
    5.   print(a);
    6. }
     
    Last edited: Jul 2, 2022
    mike6502, Bunny83, Vryken and 2 others like this.
  3. MoeinZavar

    MoeinZavar

    Joined:
    Mar 14, 2021
    Posts:
    4
    Awesome! nice explanation. Thanks.