Search Unity

Awake being called twice

Discussion in 'Scripting' started by Callski, Jul 30, 2015.

  1. Callski

    Callski

    Joined:
    Feb 3, 2013
    Posts:
    130
    Unity was working as it should. I had two hidden scripts :/.
     
    Last edited: Jul 30, 2015
  2. A.Killingbeck

    A.Killingbeck

    Joined:
    Feb 21, 2014
    Posts:
    483
    How are you determining that Awake is being called twice?
     
  3. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,537
    Agreed w/ A.Killingbeck, how do you know it's being called twice?

    Are you sure you don't have 2 of the same script attached to gameobjects in your scene?
     
  4. Callski

    Callski

    Joined:
    Feb 3, 2013
    Posts:
    130
    A debug statement. New scene + empty game object + single script with (void Awake())
     
  5. Callski

    Callski

    Joined:
    Feb 3, 2013
    Posts:
    130
    There's probably just something weird I'm doing. But putting a flag to make sure awake doesn't get called more than twice fixes it all. And I know there's not some strange second script somewhere cause the flag fixed it. If there were two separate scripts then I would have seen the message logged twice.
     
  6. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,537
    That's just a bandaid... you should figure out why Awake is being called more than once. Because it shouldn't be.

    Are you calling 'SendMessage("Awake")' anywhere?

    What does your code look like?
     
  7. Callski

    Callski

    Joined:
    Feb 3, 2013
    Posts:
    130
    Nevermind. I wrote a search script which searched for any given script in the scene. Looks like I accidentally dropped the script on something else buried in the hierarchy so there were two instances (facepalm).
     
  8. ArshakKroyan

    ArshakKroyan

    Joined:
    Mar 4, 2015
    Posts:
    32
    Hi.
    Recently I also had such an issue.
    Awake() was called twice when I exited from play mode.
    After some research through SmartGit change-logs found out that the error was after I had added
    Code (CSharp):
    1. [ExecuteInEditMode]
    for the Script.

    I hope this will help others also.
     
    jrivor, pako and L0tan like this.
  9. L0tan

    L0tan

    Joined:
    Jul 16, 2017
    Posts:
    75
    My problem was the same, did you find a workarround to fix it without removing the [ExecuteInEditMode] ?
     
    ArshakKroyan likes this.
  10. ArshakKroyan

    ArshakKroyan

    Joined:
    Mar 4, 2015
    Posts:
    32
    In my case it was ok to remove [ExecuteInEditMode].
    But you can run the body of Awake() method only when application is in "playing" state.


    Code (CSharp):
    1.     private void Awake()
    2.     {
    3.         if (Application.isPlaying)
    4.         {
    5.             // Do Something
    6.         }
    7.     }
     
    L0tan likes this.