Search Unity

Bug Variables keep switching between 0 and the value assigned in Inspector automatically.

Discussion in 'Scripting' started by Arshil111, May 29, 2023.

  1. Arshil111

    Arshil111

    Joined:
    Aug 19, 2017
    Posts:
    8
    I think this is a bug but it maybe my own mistake. Have a look. My public float variables keep switching between 0 and the value I assigned in the Inspector. I didn't define its value in the code nor did I do any operation that might have caused this.

    It isn't even for a single variable rather every variable I introduce after a certain point in time shows this behavior. I have restarted Unity.

    This particular behavior is specific to this script. I created a new script to test and didn't get this error. So maybe something I wrote is causing this without my knowledge.

    Your help will be highly appreciated. Thanks for reading

    Focus on Test float in this image Screenshot 2023-05-29 16rew3506.png


    This is the entire Script
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class PlayerMovement : MonoBehaviour
    4. {
    5.     [Header("Run")]
    6.     public float moveSpeed;
    7.     public float acceleration;
    8.     public float deAcceleration;
    9.     public float velocityPower;
    10.     public float frictionAmount;
    11.  
    12.     [Header("Jump")]
    13.     public float jumpForce;
    14.     public float jumpBufferTime;
    15.     public float jumpCoyoteTime;
    16.     [Range(0f, 1f)]
    17.     public float jumpCutMultiplier;
    18.     public float fallGravityModifier;
    19.     public float terminal;
    20.  
    21.     public float jumpHangThresold;
    22.     [Range(0f, 1f)]
    23.     public float jumpHangMultiplier;
    24.  
    25.     public Transform groundChecker;
    26.     public Vector2 groundCheckSize;
    27.     public LayerMask groundLayer;
    28.  
    29.     Rigidbody2D rb;
    30.     float moveInput;
    31.     float lastJumpTime;
    32.     float lastGroundedTime;
    33.     bool isJumping;
    34.     bool isJumpReleased;
    35.     float gravityScale;
    36.  
    37.     // Start is called before the first frame update
    38.     void Start()
    39.     {
    40.         rb = gameObject.GetComponent<Rigidbody2D>();
    41.         gravityScale = rb.gravityScale;
    42.     }
    43.     // Update is called once per frame
    44.     void Update()
    45.     {
    46.         //Monitoring the jumpbutton
    47.         if (Input.GetButtonDown("Jump"))
    48.             OnJump();
    49.         if (Input.GetButtonUp("Jump"))
    50.             OnJumpUp();
    51.  
    52.     }
    53.     public float TestFloat;
    54.     private void FixedUpdate()
    55.     {
    56.  
    57.         Debug.Log(TestFloat);
    58.  
    59.         moveInput = Input.GetAxisRaw("Horizontal");
    60.  
    61.         #region Run
    62.         //dir in which player want to go
    63.         float targetVelocity = moveInput * moveSpeed;
    64.         //current direction and target Velocity dif to find the direction and strength of force
    65.         float speedDif = targetVelocity - rb.velocity.x;
    66.  
    67.         //Deciding if we want to accelerate or deaccelerate
    68.         float accelRate = (Mathf.Abs(targetVelocity) > 0.01f) ? acceleration : deAcceleration;
    69.  
    70.         //Calculating the final dir and magnitude of movement
    71.         float movement = Mathf.Pow(Mathf.Abs(speedDif) * accelRate, velocityPower) * Mathf.Sign(speedDif);
    72.  
    73.         rb.AddForce(movement * Vector2.right);
    74.  
    75.         #endregion
    76.  
    77.         #region Friction
    78.         //Check if we are grounded and coming to a stop
    79.  
    80.         if(Mathf.Abs(Input.GetAxisRaw("Horizontal")) < 0.01f)
    81.         {
    82.             //amount of friction to be applied by taking the lesser out of current velocity and specified amount
    83.             float amountFric = Mathf.Min(Mathf.Abs(rb.velocity.x), Mathf.Abs(frictionAmount));
    84.  
    85.             //determining direction of motion
    86.             amountFric *= Mathf.Sign(rb.velocity.x);
    87.  
    88.             //apply force in opposite direction
    89.             rb.AddForce(-amountFric * Vector2.right, ForceMode2D.Impulse);
    90.         }
    91.         #endregion
    92.  
    93.         #region Jump
    94.  
    95.  
    96.         #region Timer
    97.         lastGroundedTime -= Time.deltaTime;
    98.         lastJumpTime -= Time.deltaTime;
    99.         #endregion
    100.  
    101.         //Check if player pressed jump and is grounded and is not jumping
    102.         if (lastJumpTime > 0 && lastGroundedTime > 0 && isJumping == false)
    103.         {
    104.             Jump();
    105.         }
    106.        
    107.         //Ground Checker
    108.         if(Physics2D.OverlapBox(groundChecker.position, groundCheckSize, 0, groundLayer))
    109.         {
    110.             //Check if grounded by overlap and when leaving the ground give a few secons of coyote time
    111.             lastGroundedTime = jumpCoyoteTime;
    112.             if(isJumpReleased == true)
    113.             {
    114.                 isJumping = false;
    115.             }
    116.         }
    117.  
    118.         if (isJumping && Mathf.Abs(rb.velocity.y) <= jumpHangThresold)
    119.         {
    120.             //Reduce Gravity at apex of the jump to give the effect of Hanging in air. This allows better air control
    121.             rb.gravityScale = gravityScale * jumpHangMultiplier;
    122.  
    123.             Debug.Log(jumpHangMultiplier);
    124.  
    125.         }
    126.         else if (isJumping && rb.velocity.y < 0)
    127.         {
    128.             //Extra Fall Gravity
    129.             rb.gravityScale = gravityScale * fallGravityModifier;
    130.             //Terminal Velocity
    131.             TerminalVelocity();
    132.  
    133.         }
    134.         else
    135.         {
    136.             rb.gravityScale = gravityScale;
    137.         }
    138.  
    139.         #endregion
    140.     }
    141.  
    142.     void OnJump()
    143.     {
    144.         //to be called when pressed jump button
    145.         //when jump is pressed LastJump time will not be negative hence jump can be possible
    146.         lastJumpTime = jumpBufferTime;
    147.         isJumpReleased = false;
    148.     }
    149.     void TerminalVelocity()
    150.     {
    151.         if(terminal != 0)//for some reason terminal variable keep switching between 0 and assigned value
    152.         {
    153.             rb.velocity = new Vector2(rb.velocity.x, Mathf.Max(rb.velocity.y, -terminal));
    154.         }
    155.     }
    156.  
    157.     void OnJumpUp()
    158.     {
    159.         if(rb.velocity.y > 0 && isJumping)
    160.         {
    161.             //add a downward force for JumpCut/ Vairable jump Height
    162.             rb.AddForce(Vector2.down * rb.velocity.y * (1 - jumpCutMultiplier), ForceMode2D.Impulse);
    163.         }
    164.         lastJumpTime = 0;
    165.         isJumpReleased = true;
    166.     }
    167.     private void Jump()
    168.     {
    169.         rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
    170.         lastGroundedTime = 0;
    171.         lastJumpTime = 0;
    172.         isJumping = true;
    173.     }
    174.  
    175.     private void OnDrawGizmosSelected()
    176.     {
    177.         Gizmos.color = Color.cyan;
    178.         Vector3 groundCheckerin3D = new Vector3(groundCheckSize.x, groundCheckSize.y, 1);
    179.         Gizmos.DrawWireCube(groundChecker.position, groundCheckerin3D);
    180.     }
    181. }
    182.  
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
    And to verify, you don't have multiple copies of this script in your scene? One that has default values and one that has the values you changed in the inspector?
     
    Arshil111 likes this.
  3. Arshil111

    Arshil111

    Joined:
    Aug 19, 2017
    Posts:
    8
    No only 1 script. this is the only script in this project right now actually
     
  4. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
    Only one copy in your scene itself? You can search for the script in your hierarchy, not the project window, but you can also do.

    Code (CSharp):
    1. Debug.Log(TestFloat, gameobject);
    Then, click on both debug messages in the console and see what object flashes in the scene. That object is what is printing out that message. Make sure it's correct.

    To note, while Unity isn't bug free, most of the time common features are errors on our part. Especially if you can't recreate it.
     
    Arshil111 likes this.
  5. Arshil111

    Arshil111

    Joined:
    Aug 19, 2017
    Posts:
    8
    Yes, there is only one gameObject with this script. I double-checked with Debug.Log too
     
  6. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,116
    This isn't possible. You have another instance of this script running. Now whether you wanted it and/or knew about it is something else. Maybe you're creating a copy in the play mode.

    Don't assume things backward. If a value gets logged, a value gets logged, meaning there is a value that gets logged, whether you can remember doing that or not doesn't matter. Unity doesn't have any such glaring issues with how these things work. Ever.
     
    Arshil111 likes this.
  7. Arshil111

    Arshil111

    Joined:
    Aug 19, 2017
    Posts:
    8
    I checked every game object in my scene once again. There is only one gameObject with this script and the value of the variable indeed keep switching. The thing is that this is only for the last two variables I introduced. All the variables before that are working fine.
    If there were more than one instance of this script in my scene, the variables I introduced earlier would also have shown similar behavior but that's after logging those working variables I found out that's not the case.
     
  8. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,938
    I hate to repeat what everyone else has said but the only possible way for this to happen would be more than one component in the scene. This genuinely does not happen.

    Try something like this to see for certain whether this is more than one component in the scene:
    Code (CSharp):
    1. [UnityEditor.MenuItem("Testing/Print Component Count")]
    2. private static void PrintComponentCount()
    3. {
    4.     var components = FindObjectsByType<DebugLogTesting>(FindObjectsSortMode.None);
    5.     Debug.Log("Component Count:" + components.Length);
    6.     foreach (var component in components)
    7.     {
    8.         Debug.Log(component.name, component);
    9.     }
    10. }
     
    Arshil111 likes this.
  9. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,639
    All I'm seeing is two numbers. How do you know they are both testFloat? I see other Debug.Log statements in there too, like one for jumpHangMultiplier. Are you sure they are both even from the same script? You should add some kind of label to your Debug.Log so you can see where it's coming from.
     
  10. Arshil111

    Arshil111

    Joined:
    Aug 19, 2017
    Posts:
    8
    I feel insanely stupid now. The thing was two Player Movement scripts were attached to my player.
    I am sorry for wasting everyone's time and Thanks for helping me @kdgalla @spiney199 @orionsyndrome @Brathnann
     
    Chubzdoomer likes this.