Unity中的线程

问:

I've done some searching on this board and never really found any posts that answer my question.

I've also looked up the unity script reference for coroutine and yield. I don't fully get what they do based on that description.

Here's my scenario:

I'm creating a piece of training software for disassembling/reassembling/describing parts of guns and other equipment.

Right now the feature I'm implementing is a second camera pointing away from where the main action is going on, when a component is clicked I instantiate a clone in front of that camera. This second camera is displayed in the upper left corner of the screen. The component display is rotatable by the user and information about the piece is displayed.

HOWEVER, since I'm instantiating clones, some of the components have somewhat complicated geometry and take a little time to load which in turn freezes the whole program until the object is instantiated.

I want to do these instantiations in a separate thread and display "loading" text in the smaller camera window so that only that feature is out of commission while the instantiation is happening.

In other programming environments I know how to manage threads. In unity, I do not.

Are coroutines the unity word for threads? Are they different? Should I use a thread or coroutine? Can someone show me an example or two?

Your help is much appreciated : ]


回答:

Ok just to sum it up again because it seems Eric's answer wasn't enough (but it actually should ;) ):

  • Unity's Api is NOT thread safe so it can't be used from another thread. Unity have also implemented a thread-check to prevent you from trying to use it from another thread :D
  • The scripting environment is just plain and simple .NET / Mono so if you really want to start a new thread, read intothe C# docs.
  • You can use your own threads for calculating something in the background or communicate with a native code plugin but not to interact with Unity.
  • Coroutines implement an cooperative multitasking system and they aren't invented by Unity. Unity uses .NET / Mono Generators to implement them. If you're interested in how they work see this post.
  • As already mentioned Instantiate is an atomic operation (can't be divided into smaller parts) so it runs until it's done. If it loads a really huge thing there's no way to speed it up.
  • If you have Unity pro you could place the stuff you need into a seperate scene and load this with Unity's own background loading thread by using Application.LoadLevelAdditiveAsync. This allows you to load it in the background, but it's much slower than the straight-forward functions because it's designed to keep the framerate at an acceptable level.


你可能感兴趣的:(Unity中的线程)