Home > OS >  script doesn't work when I use == 0, but with > 0, its not working as intended
script doesn't work when I use == 0, but with > 0, its not working as intended

Time:03-13

I made this script to check is the magazineSize from Gun script is equal to 0, if yes I need to disable weaponRecoilCS and cameraRecoilCS, but its not working, but when I try using:

if (gunCS.magazineSize > 0) the scripts get turned off, and when I change it back to: (gunCS.magazineSize == 0) nothing happen the scripts does not turn off.

and this is the script that I am using:


using UnityEngine;

public class RecoilDisabler : MonoBehaviour
{
    WeaponRecoil weaponRecoilCS;
    CameraRecoil cameraRecoilCS;
    Gun gunCS;

    [SerializeField] GameObject gun;
    [SerializeField] GameObject camRecoilObj;

    void Awake()
    {
        gunCS = gun.GetComponent<Gun>();
        weaponRecoilCS = gun.GetComponent<WeaponRecoil>();
        cameraRecoilCS = camRecoilObj.GetComponent<CameraRecoil>();
    }

    void Update()
    {
        if (gunCS.magazineSize == 0)
        {
            weaponRecoilCS.enabled = false;
            cameraRecoilCS.enabled = false;
        }
        else if (gunCS.magazineSize < 0)
        {
            weaponRecoilCS.enabled = true;
            cameraRecoilCS.enabled = true;
        }

    }
}

CodePudding user response:

You can try:

<=

Since > 0 makes it work even if its higher than 0.

CodePudding user response:

Try to convert to appropriate data type and then do the comparison, I have imagined that magazineSize is Integer so I have converted the gunCS.magazineSize to Integer and then do the comparison, just like this

int magazineSize = 0;
int.TryParse(gunCS.magazineSize.ToString(), out magazineSize); 

Now, if you check you should get the result you want,

if (magazineSize == 0)
        {
            // YOUR CODE FOR EQUAL TO ZERO
        }
        else
        {
            // YOUR CODE FOR NOT EQUAL TO ZERO
        } 

just like the following:

int magazineSize = 0;
int.TryParse(gunCS.magazineSize.ToString(), out magazineSize); 

if (magazineSize == 0)
{
    // YOUR CODE FOR EQUAL TO ZERO
}
else
{
    // YOUR CODE FOR NOT EQUAL TO ZERO
}

If it helped you, then please upvote the answer :)

  • Related