Search Unity

Update weirdness. Am I missing something silly?

Discussion in 'Scripting' started by AntFitch, Jun 5, 2013.

  1. AntFitch

    AntFitch

    Joined:
    Jan 31, 2012
    Posts:
    243
    If I disable then enable a script, Update() doesn't reset. Update() continues from where it left off before the script was disabled.

    For example:

    Code (csharp):
    1.  
    2.     void OnEnable()
    3.     {
    4.             test = new int[4] {10,20,30,40};
    5.     }
    6.  
    7.     void Update()
    8.     {
    9.         for (int i=0; i<test.Length; i++)
    10.         {
    11.             // after disable  re-enable script, OnEnable is called, but when Update is called right afterwards,
    12.             // Update jumps to the line below  skips the "for" line. So, if "i" was 2 when script was disabled, it is still 2 when script is enabled and hits this line.
    13.             ExecuteAction(test[i]);
    14.         }
    15.     }
    16.  
    Is there a way to ensure Update resets when a script is disabled? I'm using the enable property to reset the script. Maybe there is a better way to make it stop and refresh?
     
  2. JamesLeeNZ

    JamesLeeNZ

    Joined:
    Nov 15, 2011
    Posts:
    5,616
    how is that code supposed to 'reset' exactly?

    why would you even want Update to reset... what youre saying is illogical.
     
  3. cdevl

    cdevl

    Joined:
    Apr 10, 2013
    Posts:
    180
    Unless you are using coroutines somewhere (that you are not showing here) the execution cannot just stop in the middle and pickup where it left off. Update() is executed exactly once per frame. You are missing something.
     
  4. AntFitch

    AntFitch

    Joined:
    Jan 31, 2012
    Posts:
    243
    @JamesLeeNZ
    Because you don't understand my question does not make it illogical.

    You're right cdevl, I was missing something. After the script was disabled and then enabled, the code inside ExecuteAction() continued where it left off. Thus, because some values no longer existed, the debugger jumped to the ExecuteAction line in Update().
     
  5. JamesLeeNZ

    JamesLeeNZ

    Joined:
    Nov 15, 2011
    Posts:
    5,616
    Its not that I don't understand your question. Its more that you don't understand what youre doing.