I'm currently coding an RPG engine in XNA. The engine executes a seri开发者_C百科es of scripting commands but has to block until the next scripting command. How can I do this?
For example:
// interact with an NPC named in String 'Name'
String interactfunc = String.Format("{0}_Interact", Name);
System.Reflection.MethodInfo info = Factory.Script.GetType().GetMethod(interactfunc);
if (info != null) info.Invoke(Factory.Script, new object[]{this});
//this may run the following script command for NPC 'Bob'
public void Bob_Interact(NPC Bob)
{
Bob.Say("Well this worked.");
Bob.Say("Didnt it?");
}
//the say command looks like this
public void Say(String Text)
{
TalkGui gui = new TalkGui(this, Text);
Factory.Game.Guis.Add(gui);
Factory.FocusedGui = gui;
}
Now I need the script the wait until the first TalkGui has been dismissed before running the next script command.
What's the best way to do this? Maybe run the script functions in their own thread or something?
You don't want to use threads for this kind of thing. They're far too heavy weight.
What you really want is co-routines. You can emulate these in C# using yield
and iterators.
There are some examples here and here. And perhaps my answer here is worth reading too.
C# 5.0 is introducing a much nicer way of doing asynchronous programming like this. Here's a video and here is the CTP.
精彩评论