Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

The FPS default script drops my games frame rate?

Discussion in 'Scripting' started by Treasureman, May 19, 2016.

  1. Treasureman

    Treasureman

    Joined:
    Jul 5, 2014
    Posts:
    563
    I'm using the Unity default First Person script, and I'm having an issue. My game runs at about 55 - 60 fps, but when I sprint, the game drops down to about 27 - 30 fps. I changed a few things, but nothing that should do that. Why is this? Here's the script...
    Code (CSharp):
    1. using System;
    2. using UnityEngine;
    3. using UnityStandardAssets.CrossPlatformInput;
    4. using UnityStandardAssets.Utility;
    5. using Random = UnityEngine.Random;
    6.  
    7. namespace UnityStandardAssets.Characters.FirstPerson
    8. {
    9.     [RequireComponent(typeof (CharacterController))]
    10.     [RequireComponent(typeof (AudioSource))]
    11.     public class FirstPersonController : MonoBehaviour
    12.     {
    13.  
    14.         public GameObject staminaBar;
    15.  
    16.         [SerializeField] private bool m_IsWalking;
    17.         [SerializeField] private float m_WalkSpeed;
    18.         [SerializeField] private float m_RunSpeed;
    19.         [SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten;
    20.         [SerializeField] private float m_JumpSpeed;
    21.         [SerializeField] private float m_StickToGroundForce;
    22.         [SerializeField] private float m_GravityMultiplier;
    23.         [SerializeField] private MouseLook m_MouseLook;
    24.         [SerializeField] private bool m_UseFovKick;
    25.         [SerializeField] private FOVKick m_FovKick = new FOVKick();
    26.         [SerializeField] private bool m_UseHeadBob;
    27.         [SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob();
    28.         [SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob();
    29.         [SerializeField] private float m_StepInterval;
    30.         [SerializeField] private AudioClip[] m_FootstepSounds;    // an array of footstep sounds that will be randomly selected from.
    31.         [SerializeField] private AudioClip m_JumpSound;           // the sound played when character leaves the ground.
    32.         [SerializeField] private AudioClip m_LandSound;           // the sound played when character touches back on ground.
    33.         public GameObject disable;
    34.         public GameObject disable2;
    35.  
    36.         private Camera m_Camera;
    37.         private bool m_Jump;
    38.         private float m_YRotation;
    39.         private Vector2 m_Input;
    40.         private Vector3 m_MoveDir = Vector3.zero;
    41.         private CharacterController m_CharacterController;
    42.         private CollisionFlags m_CollisionFlags;
    43.         private bool m_PreviouslyGrounded;
    44.         private Vector3 m_OriginalCameraPosition;
    45.         private float m_StepCycle;
    46.         private float m_NextStep;
    47.         private bool m_Jumping;
    48.         private AudioSource m_AudioSource;
    49.  
    50.         // Use this for initialization
    51.         private void Start()
    52.         {
    53.             m_CharacterController = GetComponent<CharacterController>();
    54.             m_Camera = Camera.main;
    55.             m_OriginalCameraPosition = m_Camera.transform.localPosition;
    56.             m_FovKick.Setup(m_Camera);
    57.             m_HeadBob.Setup(m_Camera, m_StepInterval);
    58.             m_StepCycle = 0f;
    59.             m_NextStep = m_StepCycle/2f;
    60.             m_Jumping = false;
    61.             m_AudioSource = GetComponent<AudioSource>();
    62.             m_MouseLook.Init(transform , m_Camera.transform);
    63.         }
    64.  
    65.  
    66.         // Update is called once per frame
    67.         private void Update()
    68.         {
    69.             RotateView();
    70.             // the jump state needs to read here to make sure it is not missed
    71.             if (!m_Jump)
    72.                 if (disable.activeSelf)
    73.             {
    74.                 m_Jump = CrossPlatformInputManager.GetButtonDown("Jump") && m_CharacterController.isGrounded;
    75.             }
    76.  
    77.             if (!m_PreviouslyGrounded && m_CharacterController.isGrounded)
    78.             {
    79.                 StartCoroutine(m_JumpBob.DoBobCycle());
    80.                 PlayLandingSound();
    81.                 m_MoveDir.y = 0f;
    82.                 m_Jumping = false;
    83.             }
    84.             if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded)
    85.             {
    86.                 m_MoveDir.y = 0f;
    87.             }
    88.  
    89.             m_PreviouslyGrounded = m_CharacterController.isGrounded;
    90.         }
    91.  
    92.  
    93.         private void PlayLandingSound()
    94.         {
    95.             m_AudioSource.clip = m_LandSound;
    96.             m_AudioSource.Play();
    97.             m_NextStep = m_StepCycle + .5f;
    98.         }
    99.  
    100.  
    101.         private void FixedUpdate()
    102.         {
    103.             float speed;
    104.             GetInput(out speed);
    105.             // always move along the camera forward as it is the direction that it being aimed at
    106.             Vector3 desiredMove = transform.forward*m_Input.y + transform.right*m_Input.x;
    107.  
    108.             // get a normal for the surface that is being touched to move along it
    109.             RaycastHit hitInfo;
    110.             Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo,
    111.                                m_CharacterController.height/2f, ~0, QueryTriggerInteraction.Ignore);
    112.             desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized;
    113.  
    114.             m_MoveDir.x = desiredMove.x*speed;
    115.             m_MoveDir.z = desiredMove.z*speed;
    116.  
    117.  
    118.             if (m_CharacterController.isGrounded)
    119.             {
    120.                 m_MoveDir.y = -m_StickToGroundForce;
    121.  
    122.                 if (m_Jump)
    123.                 {
    124.                     m_MoveDir.y = m_JumpSpeed;
    125.                     PlayJumpSound();
    126.                     m_Jump = false;
    127.                     m_Jumping = true;
    128.                 }
    129.             }
    130.             else
    131.             {
    132.                 m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime;
    133.             }
    134.             m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime);
    135.  
    136.             ProgressStepCycle(speed);
    137.             UpdateCameraPosition(speed);
    138.  
    139.             m_MouseLook.UpdateCursorLock();
    140.         }
    141.  
    142.  
    143.         private void PlayJumpSound()
    144.         {
    145.             m_AudioSource.clip = m_JumpSound;
    146.             m_AudioSource.Play();
    147.         }
    148.  
    149.  
    150.         private void ProgressStepCycle(float speed)
    151.         {
    152.             if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0))
    153.             {
    154.                 m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))*
    155.                              Time.fixedDeltaTime;
    156.             }
    157.  
    158.             if (!(m_StepCycle > m_NextStep))
    159.             {
    160.                 return;
    161.             }
    162.  
    163.             m_NextStep = m_StepCycle + m_StepInterval;
    164.  
    165.             PlayFootStepAudio();
    166.         }
    167.  
    168.  
    169.         private void PlayFootStepAudio()
    170.         {
    171.             if (!m_CharacterController.isGrounded)
    172.             {
    173.                 return;
    174.             }
    175.             // pick & play a random footstep sound from the array,
    176.             // excluding sound at index 0
    177.             int n = Random.Range(1, m_FootstepSounds.Length);
    178.             m_AudioSource.clip = m_FootstepSounds[n];
    179.             m_AudioSource.PlayOneShot(m_AudioSource.clip);
    180.             // move picked sound to index 0 so it's not picked next time
    181.             m_FootstepSounds[n] = m_FootstepSounds[0];
    182.             m_FootstepSounds[0] = m_AudioSource.clip;
    183.         }
    184.  
    185.  
    186.         private void UpdateCameraPosition(float speed)
    187.         {
    188.             Vector3 newCameraPosition;
    189.             if (!m_UseHeadBob)
    190.             {
    191.                 return;
    192.             }
    193.             if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded)
    194.             {
    195.                 m_Camera.transform.localPosition =
    196.                     m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude +
    197.                                       (speed*(m_IsWalking ? 1f : m_RunstepLenghten)));
    198.                 newCameraPosition = m_Camera.transform.localPosition;
    199.                 newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset();
    200.             }
    201.             else
    202.             {
    203.                 newCameraPosition = m_Camera.transform.localPosition;
    204.                 newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset();
    205.             }
    206.             m_Camera.transform.localPosition = newCameraPosition;
    207.         }
    208.  
    209.  
    210.         private void GetInput(out float speed)
    211.         {
    212.             // Read input
    213.             float horizontal = CrossPlatformInputManager.GetAxis("Horizontal");
    214.             float vertical = CrossPlatformInputManager.GetAxis("Vertical");
    215.  
    216.             bool waswalking = m_IsWalking;
    217.  
    218. #if !MOBILE_INPUT
    219.             // On standalone builds, walk/run speed is modified by a key press.
    220.             // keep track of whether or not the character is walking or running
    221.      
    222.                 m_IsWalking = !Input.GetButton("Sprint");
    223.  
    224. #endif
    225.  
    226.  
    227.  
    228.                 if (disable2.activeSelf)
    229.                     {
    230.                         m_RunSpeed = 3;
    231.                     }
    232.  
    233.                 if (disable.activeSelf)
    234.                     {
    235.                         m_RunSpeed = 8;
    236.                     }
    237.  
    238.                 if (Input.GetButton("Sprint") && Input.GetAxis("Horizontal") != 0 || Input.GetButton("Sprint") && Input.GetAxis("Vertical") != 0)
    239.                     if(disable.activeSelf)
    240.                     {
    241.                         m_GravityMultiplier = 0.75f;
    242.                     }
    243.                 if (Input.GetButtonUp("Sprint"))
    244.                     {
    245.                         m_GravityMultiplier = 3.5f;
    246.                     }
    247.                 // set the desired speed to be walking or running
    248.  
    249.                 speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed;
    250.                 m_Input = new Vector2(horizontal, vertical);
    251.        
    252.  
    253.             // normalize input if it exceeds 1 in combined length:
    254.             if (m_Input.sqrMagnitude > 1)
    255.             {
    256.                 m_Input.Normalize();
    257.             }
    258.  
    259.             // handle speed change to give an fov kick
    260.             // only if the player is going to a run, is running and the fovkick is to be used
    261.             if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0)
    262.             {
    263.                 StopAllCoroutines();
    264.                 StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown());
    265.             }
    266.         }
    267.  
    268.  
    269.         private void RotateView()
    270.         {
    271.             m_MouseLook.LookRotation (transform, m_Camera.transform);
    272.         }
    273.  
    274.  
    275.         private void OnControllerColliderHit(ControllerColliderHit hit)
    276.         {
    277.             Rigidbody body = hit.collider.attachedRigidbody;
    278.             //dont move the rigidbody if the character is on top of it
    279.             if (m_CollisionFlags == CollisionFlags.Below)
    280.             {
    281.                 return;
    282.             }
    283.  
    284.             if (body == null || body.isKinematic)
    285.             {
    286.                 return;
    287.             }
    288.             body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse);
    289.         }
    290.     }
    291. }
    292.  
     
  2. Xarbrough

    Xarbrough

    Joined:
    Dec 11, 2014
    Posts:
    1,184
    Have you tried using the Profile with Deep Profile enabled? It can tell you exactly which method calls take how long. Do a few test runs and see if you can find any abnormalities. Then maybe post some screenshots of the Profiler data. If the performance drop only occurs when you sprint, it might be the sprint code, but it also might be something completely different; the Profiler knows. ;)
     
  3. Treasureman

    Treasureman

    Joined:
    Jul 5, 2014
    Posts:
    563
    How do I do that?
     
  4. Xarbrough

    Xarbrough

    Joined:
    Dec 11, 2014
    Posts:
    1,184
  5. Treasureman

    Treasureman

    Joined:
    Jul 5, 2014
    Posts:
    563
    Okay, I looked at it and ran some tests, and it's not actually the FPS Script, but a motion blur that appears whenever you sprint. How could I make the game run smoother while still keeping the camera blur?
     
  6. Xarbrough

    Xarbrough

    Joined:
    Dec 11, 2014
    Posts:
    1,184
    There is not easy answer to this kind of questions. Generally: Optimize everything that runs slow. If the profiler says, the motion blur takes the longest time, you should reduce its iteration count or crank all values back some. But of course there are many other factors. Reduce the complexity of models, shaders, amount of assets etc. There's no magic solution, you just need to turn everything down.
     
  7. Dave-Carlile

    Dave-Carlile

    Joined:
    Sep 16, 2012
    Posts:
    967
    The first thing I do when starting any new game is turn off motion blur because it's usually way over done and makes me nauseous and I know many others who do the same. You might re-evaluate if you even need it at all, or crank down the settings so it's very subtle (and presumably performs better). Less is more, as they say.