Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by JPB18 · Jul 02, 2013 at 03:08 PM · gamestartupasynccalculations

Async Calculations in a level

Hey there!

So I'm trying to make a script at the game startup (Lets call it Scene 0) where the script checks the current screen resolution and scales the gui dimensions at start, while showing a progress bar/circle. I've been checking the Application.LoadLevelAsync, but I believe that's only good for loading an entire level, not to run a script.

So, is there any way to run a script in a Asyncronous way?

Thanks in advance, João Borrego.

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by Briksins · Dec 17, 2013 at 11:57 AM

you can use Async - native C# functionality, it is nothing to do with Unity however it is depends on the Unity main thread, and if you try to execute Unity Thread depending stuff (for example: WWW or WWWForm) you will get error. However even than could be ignored and manually implemented through native C# WebClient class

it is slightly complex and require use of C# delegates, also actual class where you going to implement async routine shouldn't extend MonoDeveloper class

here is example:

Lets say we create simple C# script and attach it to the Main Camera

MyAsyncExecutor.cs - Class to attache to Main Camera

 public class MyAsyncExecutor: MonoBehaviour {
 
     // Use this for initialization
     void Start () {
         AsyncController ac = new AsyncController();
         ac.StartAsyncCalculation();
     }
     
     // Update is called once per frame
     void Update () {
     
     }
 }

Create AsyncController.cs class NOTE: dont extend MonoDeveloper

 public class AsyncController {
            //int is async return type                  //arguments
     private delegate int AsyncCalculatorDelegator(int dig1, int dig2);
     
     public void StartAsyncCalculation()
     {
         // Create delegate and define what it going to do 
         //in this example it will call "int AsyncCalculator.Calculate(int, int)"
         AsyncCalculatorDelegator myDelegate = new AsyncCalculatorDelegator(new AsyncCalculator.Calculate);
         
         int dig1 = 10;
         int dig2 = 20;
         //Now Execute it asynchronously by passing arguments and defining event response method 
         myDelegate.BeginInvoke(dig1, dig2, new AsyncCallback(CalculationResponse), null);
     }
     
     public void CalculationResponse(IAsyncResult result)
     {
         //lazy recast
         AsyncResult res = (AsyncResult)result;
         //getting delegate back
         AsyncCalculatorDelegator myDelegate = (AsyncCalculatorDelegator)res.AsyncDelegate;
         //getting actual result from async calculation
         int sumResult = myDelegate.EndInvoke(result);
         
         //now you can do with sumResult whatever you want as it was calculated Async-ly
     }
 }

Finally create class where you will do actual calculation: AsyncCalculator.cs

 public class AsyncCalculator {
     
     public int Calculate(int dig1, int dig2)
     {
         //do your calculations here
         //and return result as declared type
         //in this case it should be int
         
         int sum = dig1 + dig2;
         return sum;
     }
 }

here you are :) you did sum calculation in async way :)

There are new features in .Net 4.5 with use of "async" "Task" and "await" it is much easier to use it, however im not sure yet how Unity will handle it, as Unity create by default C# project in .Net 3.5 and "Task" is not available in 3.5

as you see there are 4 other ways of implementing parallel calculations which I found so far, they are:

  • "StartCorutine", "IEnumereble" and "yield" - native Unity thing

  • "Delegates", "BeginEnvoke" and "EndEnvoke" - example I showed

  • "Task" and "await" = new thing in .Net 4.5

  • "Threads" - never look at it yet in C#

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image JPB18 · Dec 22, 2013 at 04:08 PM 0
Share

Well, lets hope this fits the glove! Since most of those operations are read from file, and then return the contents, it might be perfect :P

avatar image
2

Answer by InfiniBuzz · Jul 02, 2013 at 03:46 PM

Have you tried / thought of using a coroutine and events?

Comment
Add comment · Show 5 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Julien-Lynge · Jul 02, 2013 at 03:52 PM 1
Share

As InfiniBuzz mentioned, coroutines are somewhat asynchronous, in that they can be paused between frames. This is probably your best bet.

I feel it's worth mentioning that you can also use threads with Unity, but the Unity API itself is not thread safe, so you can only do things in Unity from the main thread. Other threads can be used if you're doing intensive calculations (e.g. for AI) that you want to run in parallel.

avatar image JPB18 · Jul 05, 2013 at 01:13 PM 0
Share

I already considered using Coroutines, but aren't they frame dependent, too? I mean, everytime I use a coroutine, I usually include a "yield WaitFor..." or something like that...

avatar image InfiniBuzz · Jul 05, 2013 at 01:20 PM 1
Share

What do you mean exactly frame dependent?

Give more infaormation about what you want to do?

1) Load a gamescene and display a loading overlay till the scene is fully loaded? (this is basically not possible)

2) Load a "splashScreenScene" first and do calculations and then load the gamescene? In this you can use coroutines but also do it "normally".

avatar image ToruTheRedFox InfiniBuzz · May 30, 2020 at 10:03 AM 0
Share

Actually 1 is possible and I've done it multiple times, even with full animation

avatar image JPB18 · Jul 25, 2013 at 12:20 PM 0
Share

InfiniBuzz, it was the option number 2.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

19 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

getting udp package info inside unity (GlovePIE) 0 Answers

Help; I have two code errors need adivce 0 Answers

End game then an Object is close to another object? 0 Answers

Scripting error #2! 2 Answers

get all scripts attached to gameobject 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges