2013-08-20 62 views
0

我有一个在我的场景中被调用过几次的协程。我想创建一个全局数组以便监听事件

IEnumerator Save_assets(string file, int i, string name){ 

    var filename = Path.GetFileName(file); 
    docPath = Application.streamingAssetsPath+"/files/"; 
    var temp_name = docPath+filename; 

    downloaded_asset = false; 

    if(!Directory.Exists(docPath)){ 
     Directory.CreateDirectory(docPath); 
    } 

    if (!System.IO.File.Exists(temp_name)){ 
     WWW www = new WWW(file); 
     yield return www; 
     //Save the image 
     System.IO.File.WriteAllBytes(temp_name, www.bytes); 
    } 

    /* I really would like to have a sort of listener here doing something like: 
     //pseudocode 
     while(global.file != true){ //while not done 
      yield return null; 
     } 

    */ 
    downloaded_asset = true; 
    finished = false; 
    tries = 0; 

    go = GameObject.Find(name); 
    go.gameObject.BroadcastMessage("paint_file", temp_name); 

} 

一旦paint_file已经上调用非常类 不断寻找特定条件发生了更新功能,让我们说这是“完成=真;”

void paint_file(file){ 
    [...]//code 
} 

void Update() { 
    var done = true;//let's pretend there's no code here, just done = true 
    if(done){ 
     Debug.Log("Finished: "+paint_file._filename); 
    } 
} 

我不知道该如何设置VAR global.file =完成, 任何帮助,将不胜感激

+0

这个问题的标题是关于为描述为“我想在Visual Basic中的GUI跟踪一个IP地址“。首先,这不是一个问题,而是一个陈述。对于两个,标题告诉我们一个无效或不良实践的解决方案,而不是要求一个有效的或最佳实践的解决方案的基本问题。 –

+0

您的评论同样糟糕,这是我与C#合作的第七天,难道你不认为如果我知道我可以管理什么?此外,很好的参考大家看电视 – sathia

回答

1

避免使用以往的全局(静态或单身)使用直接回调,而不是或钩东西了与组件/对象引用

也避免查找,broadcastMessage理想的,因为它们是缓慢:-)

,而不是有:

var SomeComponentType myReferenceToThatComponent; 

on Awake(){ 
    if(myReferenceToThatComponent==null){ 
     myReferenceToThatComponent = GetComponent<SomeComponentType>(); 
    } 
} 

一旦你有一个组件的引用,你可以访问任何公共物品如:

myReferenceToThatComponent.done = true; 
myReferenceToThatComponent.SomeMethod(true); 

的好处是你可以设置在编辑器参考,但如果你不把它留下它是空的,它会去尝试找到它,它只会找到它一次,任何进一步的使用将使用缓存的结果,而不必再次使用昂贵的搜索。

您的www应该被包围的“使用”因为是常见的做法,以确保它完成

using (WWW www = new WWW(url, form)) { 
    yield return www; 

} 

时的方法来寻找和获取组件和对象的无数超出范围垃圾收集这个答案我认为

只记得Unity最好是基于组件的,它与C#编码的典型OOP继承/接口风格完全不同。

-

的方法来组织协同程序运行了一个又一个等待一个完成:

void Start() { 
    StartCoroutine(BaseRoutine()); 
} 

IEnumerator BaseRoutine() { 
    for (int i = 0; i < 10; i++) { 
     yield return StartCoroutine(ChildRoutine(i)); 
    }  
} 

IEnumerator ChildRoutine(int i) { 
    Debug.Log("ChildRoutine number: " + i); 
    yield return new WaitForSeconds(1); // Put your yield return WWW here for example 
} 
+0

谢谢,我会尽快尝试这种方法,并可能改善代码,我不知道的一件事是,我需要留意几个对象,至少有三个子程序下载内容并等待file.done = true;用你给我看的方法,它似乎正在传播到一个单一的变量。 – sathia

+0

如果你想知道什么时候所有3人都完成了,你需要让他们把3个独立的布尔变成真,并且只有当所有3个都是真的时才能继续。或者让他们每个增加一个计数器,当这个计数器达到3然后运行(尽管如果你不小心有一个运行两次而又不能运行另一个),那么这个计数器会变得不合理。我们确信所有3个都完成了 }' – HeliosDoubleSix

+0

不幸有几个,很可能是100个元素,这就是为什么我想到了一个数组。每个协程下载一个新的项目,每个项目可以花费几分钟或几秒钟的时间 – sathia