Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question cant reference a bool in another script !

Discussion in 'Scripting' started by Dsavage13, Nov 8, 2020.

  1. Dsavage13

    Dsavage13

    Joined:
    Nov 26, 2015
    Posts:
    76
    hello, i have two scripts, m_look, and wep_switcher, ive got raycast stuff setup in my m_look script, and im trying to reference a bool called Pistol_got, to check if i have a pistol in my weapon switcher script.... i haver been ALL over google.. i CANNOT for the life of me find out why i keep getting the error

    "NullReferenceException: Object reference not set to an instance of an object
    Wep_Switcher.Update () (at Assets/Scripts/Wep_Switcher.cs:40)"


    can anyone tell me the proper way to reference a bool from another script?


    here is the relevant code:


    Code (CSharp):
    1.  
    2. public class Wep_Switcher : MonoBehaviour {
    3.  
    4.  
    5.     public int SelectedWeapon = 0;
    6.  
    7.      M_Look script;
    8.  
    9.     void Start () {
    10.         SelectWeapon();
    11.         script = gameObject.GetComponent<M_Look>();
    12.  
    13.  
    14.     }
    15.  
    16.  
    17.     void Update () {
    18.  
    19.         int PreviousSelectedWeapon = SelectedWeapon;
    20.  
    21.  
    22.         if (Input.GetAxis ("Mouse ScrollWheel") > 0f)
    23.         {
    24.             if (SelectedWeapon >= transform.childCount - 1)
    25.                 SelectedWeapon = 0;
    26.             else
    27.                 SelectedWeapon++;
    28.         }
    29.  
    30.         if (Input.GetAxis ("Mouse ScrollWheel") < 0f)
    31.         {
    32.             if(SelectedWeapon <= transform.childCount - 1)
    33.                 SelectedWeapon = 0;
    34.             else
    35.                 SelectedWeapon--;
    36.         }
    37.    
    38.         if (Input.GetKeyDown (KeyCode.Alpha1) && script.PistolGet == true)
    39.         {
    40.             SelectedWeapon = 0;
    41.         }
    42.  
    43.         if (Input.GetKeyDown (KeyCode.Alpha2) && transform.childCount >= 2)
    44.         {
    45.             SelectedWeapon = 1;
    46.         }
    47.  
    48.         if (Input.GetKeyDown (KeyCode.Alpha3) && transform.childCount >= 3)
    49.         {
    50.             SelectedWeapon = 2;
    51.         }
    52.  
    53.         if (Input.GetKeyDown (KeyCode.Alpha4) && transform.childCount >= 4)
    54.         {
    55.             SelectedWeapon = 3;
    56.         }
    57.  
    58.         if (PreviousSelectedWeapon != SelectedWeapon)
    59.         {
    60.             SelectWeapon();
    61.         }
    62.  
    63.     }
    64.  
    65.  
    66.     void SelectWeapon()
    67.     {
    68.         int i = 0;
    69.         foreach (Transform weapon in transform)
    70.         {
    71.             if (i == SelectedWeapon)
    72.                 weapon.gameObject.SetActive(true);
    73.             else
    74.                 weapon.gameObject.SetActive(false);
    75.  
    76.             i++;
    77.  
    78.         }
    79.  
    80.     }
    81.  
    82. }



    Code (CSharp):
    1.  
    2.  
    3. public class M_Look : MonoBehaviour
    4. {
    5.  
    6.     public float mouseSensitivity = 100f;
    7.     public Transform playerBody;
    8.     public Transform TheDest;
    9.     public bool ItemGot = false;
    10.     public bool PistolGet = false;
    11.     float throwForce = 40f;
    12.     Vector3 objectPos;
    13.     public bool Combat_Mode;
    14.  
    15.  
    16.  
    17.  
    18.     float xRotation = 0f;
    19.  
    20.  
    21.     void OnGUI(){
    22.         GUI.Box(new Rect(Screen.width/2,Screen.height/2, 10, 10), "1");
    23.     }
    24.     // Use this for initialization
    25.     void Start ()
    26.     {
    27.  
    28.  
    29.  
    30.  
    31.     }
    32.  
    33.  
    34.     // Update is called once per frame
    35.     void Update ()
    36.     {
    37.  
    38.  
    39.         Cursor.visible = false;
    40.         Cursor.lockState = CursorLockMode.Locked;
    41.  
    42.  
    43.  
    44.  
    45.  
    46.  
    47.         if (Combat_Mode == false) {
    48.  
    49.  
    50.  
    51.             int layer_mask = LayerMask.GetMask ("Grabbable");
    52.             int layer_mask2 = LayerMask.GetMask ("Weapon");
    53.             var ray = Camera.main.ScreenPointToRay (new Vector3 (Screen.width / 2f, Screen.height / 2f, 0f));
    54.             RaycastHit hit;
    55.  
    56.             if (Physics.Raycast (ray, out hit, 3.0f, layer_mask)) {
    57.                 GameObject Pickable = hit.transform.gameObject;
    58.                 if ((Input.GetKey (KeyCode.E) && hit.transform.tag == "Item")) {
    59.  
    60.                     ItemGot = true;
    61.                     //Pickable.GetComponent<Rigidbody> ().isKinematic = true;
    62.                     Pickable.transform.SetParent (GameObject.Find ("Obj_Dest").transform);
    63.                     Pickable.GetComponent<Rigidbody> ().useGravity = false;
    64.                     Pickable.GetComponent<Rigidbody> ().freezeRotation = true;
    65.                     Pickable.transform.position = TheDest.position;
    66.                     Pickable.GetComponent<Rigidbody> ().detectCollisions = true;
    67.                     Pickable.GetComponent<Rigidbody> ().velocity = Vector3.zero;
    68.                     Pickable.GetComponent<Rigidbody> ().angularVelocity = Vector3.zero;
    69.                    
    70.                 } else {  
    71.                     Pickable.transform.parent = null;
    72.                 //    Pickable.GetComponent<Rigidbody> ().isKinematic = false;
    73.                     Pickable.GetComponent<Rigidbody> ().freezeRotation = false;
    74.                     Pickable.GetComponent<Rigidbody> ().useGravity = true;
    75.                     ItemGot = false;
    76.  
    77.                     if (Input.GetMouseButtonDown (0)) {
    78.            
    79.                         Pickable.GetComponent<Rigidbody> ().velocity = transform.forward * throwForce;
    80.  
    81.                     }
    82.                 }
    83.             }
    84.  
    85.             if (Physics.Raycast (ray, out hit, 3.0f, layer_mask2))
    86.             {
    87.  
    88.             ////    GameObject Weapon = hit.transform.gameObject;
    89.                 if ((Input.GetKey (KeyCode.E) && hit.transform.tag == "Pistol"))
    90.                 {
    91.                     PistolGet = true;
    92.                 }
    93.  
    94.             }
    95.  
    96.  
    97.  
    98.  
    99.         }
    100.  
    101.  
    102.         //head = transform.Find("Spine_01");
    103.         float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
    104.         float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
    105.  
    106.         xRotation -= mouseY;
    107.         xRotation = Mathf.Clamp(xRotation, -90f, 90f);
    108.  
    109.         transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
    110.  
    111.         playerBody.Rotate(Vector3.up * mouseX);
    112.    
    113.    
    114.     }
    115.  
    116. }
    117.  
     
  2. adamgolden

    adamgolden

    Joined:
    Jun 17, 2019
    Posts:
    1,549
    Your error message says the problem is on line 40, but I'm guessing you deleted the "using" from the top that's why your code block references script on line 38 instead. In the future it's best to leave the code as-is so it's easier to see the problem indicated by the error.

    It's not the bool that's giving you the null reference error, it's
    script
    . You can avoid the call to GetComponent in Start if you change the declaration to
    public M_Look script;
    and drag-drop your reference into that in the Inspector.. but if you're generating it procedurally and need that call, first thing to do is make sure the script is on the same GameObject and the reference is being found. Try changing your Start to this and see what it says:
    Code (CSharp):
    1. void Start ()
    2. {
    3.   SelectWeapon();
    4.   script = gameObject.GetComponent<M_Look>();
    5.   Debug.Log("The M_Look component was " + ((script == null) ? "NOT FOUND" : "FOUND"));
    6. }
    Also, booleans are already true or false, so you don't need to say
    if (myBool == true)
    , you can just say
    if (myBool)
    for true or
    if (!myBool)
    for false. So you can simplify the line to be:
    Code (CSharp):
    1. if (Input.GetKeyDown(KeyCode.Alpha1) && script.PistolGet)
    Finally, in your M_Look, you're saying
    public bool PistolGet = false;
    , which is being serialized - so to avoid unexpected values (like if it MUST always start as false in play mode/builds and you don't mean to expose the toggle in the Inspector), you can add "using System;" to the top of your class, then do this:
    Code (CSharp):
    1. [HideInInspector, NonSerialized]
    2. public bool PistolGet = false;
    The above will ensure that it's always initialized as false and won't be serialized while still allowing it to be public. Of course if you DO want to allow checking/unchecking that in the Inspector to override the default you can ignore this - but it's still useful to know.
     
  3. Dsavage13

    Dsavage13

    Joined:
    Nov 26, 2015
    Posts:
    76
    ah, i had no idea such shortcuts existed. i had trouble with some of these modifications, but adding using system; fixed it. now the debug is saying it was not found. still not sure what im doing wrong.. it seems i have trouble whenever i need to call a feature from another script.

    in short, im trying to have a simple weapon pickup > have in inventory > use if in inventory script.

    i tried doing it on my own, because i dont want to "cheat" at it, but its apparent i dont know everything. :p

    maybe you can direct me to a better solution to what my goal is?


    EDIT

    ive been playing around with this and other bools, i just cant get them to call. no matter what... i followed what you said.. what else could it be?
     
    Last edited: Nov 8, 2020