Search code examples
unity-game-engineunityscript

Unity - When does the frameCount goes negative


I'm learning unity scripting. But I don't understand the following :

static private var lastRecalculation = -1;
    static function RecalculateValue () {
       if (lastRecalculation == Time.frameCount)
         return;
       ProcessData.AndDoSomeCalculations();
    }

I don't get the third line or the condition in the IF statement. I know its a bit amateur, but pls help. Thank You.


Solution

  • This is from the Time.frameCount documentation. This example shows how to create a function that executes only once per frame, regardless of how many objects you attach your script to. I suspect though that this example is incomplete because it never updates lastRecalculation (or it was assumed you would do so in AndDoSomeCalculations() ).

    The reason setting lastRecalculation = -1 initially is so this function runs during the first frame.

    Working version:

        static var lastRecalculation = -1;
        static function RecalculateValue () {
            if (lastRecalculation == Time.frameCount) {
                return;
            }
            lastRecalculation = Time.frameCount;
    
            Debug.Log (Time.frameCount);
            //ProcessData.AndDoSomeCalculations();
        }
        function Update () {
            RecalculateValue();     
        }
    

    Attach this script to 2 different GameObjects and run it. You will only see unique frame values 1,2,3,4,5.... even though 2 GameObjects are each calling RecalculateValue()

    Now comment out the return and run it again. Now the ProcessData portion of that code runs for both objects every frame and you'll see something like 1,1,2,2,3,3,4,4......