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

I keep getting this error: "use of unassigned local variable 'hit'". How do I fix this?

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

  1. Ninamori

    Ninamori

    Joined:
    Oct 30, 2015
    Posts:
    33
    Code (csharp):
    1.  
    2.         Ray ray = new Ray(RayOrigin.transform.position, RayOrigin.transform.forward);
    3.         RaycastHit hit;
    4.  
    5.         if (Input.GetMouseButtonDown(0) && Physics.Raycast(ray, out hit, 20f) && hit.collider.gameObject.CompareTag("Pickable"))
    6.         {
    7.             hit.rigidbody.constraints = RigidbodyConstraints.FreezeAll;
    8.         }
    9.         if (Input.GetMouseButtonUp(0))
    10.         {
    11.             hit.rigidbody.constraints = RigidbodyConstraints.None;
    12.         }
    13.  
    I keep getting this error: "use of unassigned local variable 'hit'". How do I fix this?
     
  2. DanielQuick

    DanielQuick

    Joined:
    Dec 31, 2010
    Posts:
    3,137
    On line 11 hit won't have a value, but you're still trying to access it. What are you trying to do?
     
  3. Ninamori

    Ninamori

    Joined:
    Oct 30, 2015
    Posts:
    33
    Essentially when the left mouse button is down (pressed) freeze the rigid body constraints and when I let go remove all constraints. I'm assuming I need to log/store the rigid body somehow? I guess...
     
  4. Ninamori

    Ninamori

    Joined:
    Oct 30, 2015
    Posts:
    33
    Well I got what I wanted to work... kind of... It now freezes the constraints on LMB press and then releases them when the LMB is released. Problem is the release portion (when the LMB is released) relies on a raycast and it doesn't always hit (depending on where the player is looking). There must be a better way.

    Current Code...

    Code (csharp):
    1.  
    2.         Ray ray = new Ray(RayOrigin.transform.position, RayOrigin.transform.forward);
    3.         RaycastHit hit;
    4.  
    5.         if (Input.GetMouseButtonDown(0) && Physics.Raycast(ray, out hit, 20f) && hit.collider.gameObject.CompareTag("Pickable"))
    6.         {
    7.             hit.rigidbody.constraints = RigidbodyConstraints.FreezePositionZ | RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationY | RigidbodyConstraints.FreezeRotationZ;
    8.         }
    9.         if (Input.GetMouseButtonUp(0) &&  Physics.Raycast(ray, out hit, 20f) && hit.collider.gameObject.CompareTag("Pickable"))
    10.         {
    11.             hit.rigidbody.constraints = RigidbodyConstraints.None;
    12.         }
    13.  
     
  5. ThermalFusion

    ThermalFusion

    Joined:
    May 1, 2011
    Posts:
    906
    Store the rigidbody you hit pressing down in a class variable. Then release from this instead of ratcheting again.