Search Unity

FPS Counter Learn

Discussion in 'Community Learning & Teaching' started by ImKidenzz, Nov 27, 2022.

  1. ImKidenzz

    ImKidenzz

    Joined:
    Nov 2, 2022
    Posts:
    1
    Could someone explain that code for me?

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class FPS : MonoBehaviour
    6. {
    7.     private float pollingTime = 0.1f;
    8.     private float time;
    9.     private int frameCount;
    10.    
    11.     void Update()
    12.     {
    13.         time += Time.deltaTime;
    14.  
    15.         frameCount++;
    16.  
    17.         if (time >= pollingTime)
    18.         {
    19.             int frameRate = Mathf.RoundToInt(frameCount / time);
    20.             print(frameRate.ToString() + "FPS");
    21.  
    22.             time -= pollingTime;
    23.             frameCount = 0;
    24.         }
    25.     }
    26. }
    27.  
     
  2. unofficialgaming

    unofficialgaming

    Joined:
    Jan 2, 2018
    Posts:
    11
    Yea it seems to be a pretty simple script for counting the frames per second, so lines 7 to 9 are defining variables for the script.

    all the code within the update function is running once per frame. so line 13 is adding to the time variable Time.deltaTime this is the amount of time that has passed since the last update function basically this will allow the variable to keep track of how much time is passing.

    line 15 is adding 1 to the frameCount variable everytime the update function runs which is once per frame. so this variable is being used to count the frames.

    the if statement is checking if more that 0.1 seconds (pollingTime Variable) has passed. when this is true it runs lines 19 to 23.

    line 19 is creating a new variable called frameRate which is equal to the frameCount (the amount of frames that have happened divided by the time that has passed) and then the Mathf.RoundToInt is taking this number and converting it into a integer.

    line 20 is printing the frameRate that being calculated to a string (basically converting the information to text)

    line 22 is taking away the pollingTime from the time variable (I have a feeling this probably isn't the best way to do this script)

    line 23 sets the frameCount back to zero.

    Hope this helps :)