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'm trying to adjust the mouse sensitivity of the First Person Controller using a slider in game.

Discussion in 'Scripting' started by sirhotalot, Sep 9, 2014.

  1. sirhotalot

    sirhotalot

    Joined:
    Sep 9, 2014
    Posts:
    9
    Hello, I'm trying to adjust the mouse sensitivity of the First Person Controller using a slider in game. Here's the code I'm using:
    Code (csharp):
    1. GUI.Label(Rect(550,260,100,40), "Mouse Sensitivity");
    2. GetComponent(MouseLook).sensitivityX = GetComponent(MouseLook).sensitivityY = GUI.HorizontalSlider(new Rect(0,0,200,50), GetComponent(MouseLook).sensitivityX, 1, 20);
    Here's the error I'm getting:

    Code (csharp):
    1. NullReferenceException: Object reference not set to an instance of an object
    2. NetworkManagerScript.OnGUI () (at Assets/scripts/NetworkManagerScript.js:216)
    NetworkManager I named early on, it's more like the overall game manager as it currently keeps track of most of the functions currently in the game outside of the player. I should note that it's not attached to the First Person Controller where MouseLook is.
     
  2. sirhotalot

    sirhotalot

    Joined:
    Sep 9, 2014
    Posts:
    9
    Anybody?
     
  3. sirhotalot

    sirhotalot

    Joined:
    Sep 9, 2014
    Posts:
    9
    Nobody?
     
  4. sirhotalot

    sirhotalot

    Joined:
    Sep 9, 2014
    Posts:
    9
    Anybody at all?
     
  5. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,501
    You can only reference GUI from within the void OnGUI() function. Is that it?

    Kurt
     
  6. Deecann

    Deecann

    Joined:
    Mar 17, 2010
    Posts:
    93
    You've got an error in NetworkManagerScript:216 so put 216 line code here, even if it's not attached no where compiler will throw an error if there is. Your project is compiled as whole unit, not just those parts which are on scene.
     
  7. sirhotalot

    sirhotalot

    Joined:
    Sep 9, 2014
    Posts:
    9
    It's in the OnGUI() function.

    I did post line 216.

    Code (csharp):
    1. GetComponent(MouseLook).sensitivityX = GetComponent(MouseLook).sensitivityY = GUI.HorizontalSlider(new Rect(0,0,200,50), GetComponent(MouseLook).sensitivityX, 1, 20);
    What I'm trying to do is access the MouseLook script file which contains all the functions and variables for the mouse. This is in the MouseLook script:

    Code (csharp):
    1. enum Axes {MouseXandY, MouseX, MouseY}
    2.   var Axis : Axes = Axes.MouseXandY;
    3.   public var sensitivityX = 15.0;
    4.   public var sensitivityY = 15.0;
    5.   var minimumX = -360.0;
    6.   var maximumX = 360.0;
    7.   var minimumY = -60.0;
    8.   var maximumY = 60.0;
    9.   var rotationX = 0.0;
    10.   var rotationY = 0.0;
    11.   var lookSpeed = 2.0;
    12.    
    13.   var toggle:boolean = true;
    14.   function Update ()
    15.   {
    16.  
    17.   if (Input.GetKeyDown ("escape"))
    18.   {
    19.        if (toggle)
    20.        {
    21.          Screen.lockCursor = false;
    22.          Screen.showCursor = true;
    23.          
    24.          toggle = false;
    25.  
    26.        }
    27.        else
    28.        {
    29.          Screen.lockCursor = true;
    30.          Screen.showCursor = false;
    31.          
    32.          toggle = true;
    33.        }
    34.      }
    35.  
    36.      if (toggle)
    37.      {
    38.        if (Axis == Axes.MouseXandY)
    39.     {
    40.     // Read the mouse input axis
    41.     rotationX += Input.GetAxis("Mouse X") * sensitivityX;
    42.     rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
    43.    
    44.     // Call our Adjust to 360 degrees and clamp function
    45.     Adjust360andClamp();
    46.    
    47.     // Most likely you wouldn't do this here unless you're controlling an object's rotation.
    48.     // Call our look left and right function.
    49.     //KeyLookAround();
    50.    
    51.     // Call our look up and down function.
    52.     //KeyLookUp();
    53.    
    54.     // If the user isn't pressing a key to look up, transform our X angle to the mouse.
    55.     //if (!Input.GetAxis("LookAround"))
    56.     //{
    57.     // If you don't want to allow a key to affect X, keep this line but take it out of the if
    58.     transform.localRotation = Quaternion.AngleAxis (rotationX, Vector3.up);
    59.     //}
    60.    
    61.     // If the user isn't pressing a key to look up, transform our Y angle to the mouse.
    62.     //if (!Input.GetAxis("LookUp"))
    63.     //{
    64.     // Multiply the Quaterion so we don't loose our X we just transformed
    65.     // If you don't want to allow a key to affect Y, keep this line but take it out of the if
    66.     transform.localRotation *= Quaternion.AngleAxis (rotationY, Vector3.left);
    67.     //}
    68.     }
    69.     else if (Axis == Axes.MouseX)
    70.     {
    71.     // Read the mouse input axis
    72.     rotationX += Input.GetAxis("Mouse X") * sensitivityX;
    73.    
    74.     // Call our Adjust to 360 degrees and clamp function
    75.     Adjust360andClamp();
    76.    
    77.     // if you're doing a standard X on object Y on camera control, you'll probably want to
    78.     // delete the key control in MouseX. Also, take the transform out of the if statement.
    79.     // Call our look left and right function.
    80.     //KeyLookAround();
    81.    
    82.     // Call our look up and down function.
    83.     //KeyLookUp();
    84.    
    85.     // If the user isn't pressing a key to look up, transform our X angle to the mouse.
    86.     //if (!Input.GetAxis("LookAround"))
    87.     //{
    88.     //If you don't want to allow a key to affect X, keep this line but take it out of the if
    89.     transform.localRotation = Quaternion.AngleAxis (rotationX, Vector3.up);
    90.     //}
    91.    
    92.     }
    93.     else
    94.     {
    95.     // Read the mouse input axis
    96.     rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
    97.    
    98.     // Call our Adjust to 360 degrees and clamp function
    99.     Adjust360andClamp();
    100.    
    101.     // Call our look left and right function.
    102.     //KeyLookAround();
    103.    
    104.     // Call our look up and down function.
    105.     //KeyLookUp();
    106.    
    107.     // If the user isn't pressing a key to look up, transform our Y angle to the mouse
    108.     //if (!Input.GetAxis("LookUp"))
    109.     //{
    110.     // If you don't want to allow a key to affect Y, keep this line but take it out of the if
    111.     transform.localRotation = Quaternion.AngleAxis (rotationY, Vector3.left);
    112.     //}
    113.    
    114.     }
    115.        
    116.        if (Input.GetKeyDown ("escape")) {
    117.          Screen.lockCursor = false;
    118.        }
    119.        
    120.        if (!Screen.lockCursor && Input.GetKeyDown ("escape")) {
    121.          Screen.lockCursor = true;
    122.        }
    123.  
    124.  
    125.      }
    126.   }
    127.   function KeyLookAround ()
    128.   {
    129. //  If you're not using it, you can delete this whole function.
    130. //  Just be sure to delete where it's called in Update.
    131.   // Read the mouse input axis
    132.   rotationX += Input.GetAxis("LookAround") * lookSpeed;
    133.   // Call our Adjust to 360 degrees and clamp function
    134.   Adjust360andClamp();
    135.   // Transform our X angle
    136.   transform.localRotation = Quaternion.AngleAxis (rotationX, Vector3.up);
    137.   }
    138.   function KeyLookUp ()
    139.   {
    140. //  If you're not using it, you can delete this whole function.
    141. //  Just be sure to delete where it's called in Update.
    142.   // Read the mouse input axis
    143.   rotationY += Input.GetAxis("LookUp") * lookSpeed;
    144.   // Adjust for 360 degrees and clamp
    145.   Adjust360andClamp();
    146.   // Transform our Y angle, multiply so we don't loose our X transform
    147.   transform.localRotation *= Quaternion.AngleAxis (rotationY, Vector3.left);
    148.   }
    149.   function Adjust360andClamp ()
    150.   {
    151. //  This prevents your rotation angle from going beyond 360 degrees and also
    152. //  clamps the angle to the min and max values set in the Inspector.
    153.   // During in-editor play, the Inspector won't show your angle properly due to
    154.   // dealing with floating points. Uncomment this Debug line to see the angle in the console.
    155.   // Debug.Log (rotationX);
    156.   // Don't let our X go beyond 360 degrees + or -
    157.   if (rotationX < -360)
    158.   {
    159.   rotationX += 360;
    160.   }
    161.   else if (rotationX > 360)
    162.   {
    163.   rotationX -= 360;
    164.   }  
    165.   // Don't let our Y go beyond 360 degrees + or -
    166.   if (rotationY < -360)
    167.   {
    168.   rotationY += 360;
    169.   }
    170.   else if (rotationY > 360)
    171.   {
    172.   rotationY -= 360;
    173.   }
    174.   // Clamp our angles to the min and max set in the Inspector
    175.   rotationX = Mathf.Clamp (rotationX, minimumX, maximumX);
    176.   rotationY = Mathf.Clamp (rotationY, minimumY, maximumY);
    177.   }
    178.   function Start ()
    179.   {
    180.      Screen.lockCursor = true;
    181.   // Make the rigid body not change rotation
    182.   if (rigidbody)
    183.   {
    184.   rigidbody.freezeRotation = true;
    185.   }
    186.   }
     
  8. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,501
    Break the problem down so you can single-step the problematic line.

    First do:
    MouseLook ML = GetComponent<MouseLook>();

    If you breakpoint it and ML is null, that is your problem.

    And then use the ML as you do above (ML.sensitivityx... etc.)

    Kurt
     
  9. sirhotalot

    sirhotalot

    Joined:
    Sep 9, 2014
    Posts:
    9
    So I created this:

    Code (csharp):
    1. var playerPrefab:GameObject;
    2.  
    3. //Mouse controls
    4. var ML:MouseLook;
    5.  
    6. function Awake()
    7. {
    8.    var ML = playerPrefab.GetComponent(MouseLook);
    9. }
    and changed line 216 to this:

    Code (csharp):
    1. ML.sensitivityX = ML.sensitivityY = GUI.HorizontalSlider(new Rect(100,100,200,50), ML.sensitivityX, 1, 20);
    playerPrefab has the First Person Controller in it which has the MouseLook script.

    The project runs however no slider appears. These are the errors:

    Code (csharp):
    1. NullReferenceException: Object reference not set to an instance of an object
    2. GameManager.OnGUI () (at Assets/scripts/GameManager.js:221)
     
    Last edited: Sep 15, 2014
  10. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,501
    Apologies for answering in C# before. Now I'm writing in Javascript.

    Please see the following script, and how I made a tiny project from the Unity standard assets and got the following script working.

    Code (javascript):
    1.  
    2. #pragma strict
    3.  
    4. // 2:51 PM 9/15/2014 - answering Unity3D forum:
    5. // http://forum.unity3d.com/threads/im-trying-to-adjust-the-mouse-sensitivity-of-the-first-person-controller-using-a-slider-in-game.267462
    6. //
    7. // To Use This Script:
    8. //    Import Character Controller Standard Unity Assets
    9. //    Make a new scene
    10. //    Delete the Main Camera
    11. //    Drag the First Person Controller from the standard package into your scene
    12. //    Attach this script to the root of that controller
    13. //    Place a plane under the character to keep him from falling and give you a reference
    14. //    Run. Notice no errors.
    15. //    Cbeck the debug log and see what the value of MouseLook is at Awake() time
    16.  
    17. var ML:MouseLook;
    18.  
    19. function Awake ()
    20. {
    21.     ML = gameObject.GetComponent( MouseLook);
    22.     // Is this perhaps what you want? If the MouseLook is not in the
    23.     // root of the object where you put this script, this will instead find
    24.     // it if it is in child objects.
    25. // ML = gameObject.GetComponentInChildren(MouseLook);
    26.  
    27.     Debug.Log( "MouseLook: " + ML);
    28. }
    29.  
    30. function OnGUI()
    31. {
    32.     ML.sensitivityX = ML.sensitivityY = GUI.HorizontalSlider(new Rect(100,100,200,50), ML.sensitivityX, 1, 20);
    33. }
    34.  
    35.  
    This seems to modify the sensitivity the way you would expect it should in my scene.

    Kurt
     
  11. sirhotalot

    sirhotalot

    Joined:
    Sep 9, 2014
    Posts:
    9
    I used the Debug.Log and got this:

    Code (csharp):
    1. MouseLook: FPC (MouseLook)
    2. UnityEngine.Debug:Log(Object)
    3. GameManager:Awake() (at Assets/scripts/GameManager.js:38)
    So it is being called correctly and is accessing the right script. However the slider isn't coming up. This is my entire GUI script:

    Code (csharp):
    1.  
    2. //GUI
    3. function OnGUI()
    4. {
    5.    if (!optionsMenu)
    6.    {
    7.      if(!Network.isClient && !Network.isServer)
    8.      {
    9.        playerName = GUI.TextField (Rect (btnX, btnY - 25, 200, 20), playerName, 25);
    10.        if(GUI.Button(Rect(btnX, btnY, btnW, btnH), "Start Server"))
    11.        {
    12.          Debug.Log("Starting server...");
    13.          startServer();
    14.          optionsMenu = false;
    15.          toggleMenu = false;
    16.        }
    17.  
    18.        if(GUI.Button(Rect(btnX, btnY * 1.2 + btnH, btnW, btnH), "Refresh Hosts"))
    19.        {
    20.          Debug.Log("Refreshing...");
    21.          refreshHostList();
    22.        }
    23.  
    24.        if(GUI.Button(Rect(btnX, btnY * 3.4 + btnH, btnW, btnH), "Options"))
    25.        {
    26.          Debug.Log("Loading options...");
    27.          optionsMenu = true;
    28.        }
    29.  
    30.        if(GUI.Button(Rect(btnX, btnY * 5.6 + btnH, btnW, btnH), "Exit"))
    31.        {
    32.          Debug.Log("Closing game...");
    33.          exitGame();
    34.        }
    35.  
    36.        if (hostData)
    37.        {
    38.          for(var i:int = 0; i<hostData.length; i++)
    39.          {
    40.            if(GUI.Button(Rect(btnX * 2 + btnW, btnY * 1.2 + (btnH * i), btnW * 3, btnH * .5), hostData[i].gameName))
    41.            {
    42.              Network.Connect(hostData[i]);
    43.              optionsMenu = false;
    44.              toggleMenu = false;
    45.            }
    46.          }
    47.        }
    48.      }
    49.    }
    50.  
    51.    /*else if (Input.GetKeyDown(KeyCode.Return))
    52.    {
    53.        chatting = true;
    54.    }*/
    55.  
    56.    /*if (Input.GetKeyDown(KeyCode.Return) && chatting)
    57.    {
    58.        chatting = false;
    59.    }*/
    60.  
    61.    if (chatting)
    62.    {
    63.      GUILayout.Label (log);
    64.      myMessage = GUILayout.TextField (myMessage);
    65.      if(GUILayout.Button ("Send Message"))
    66.      {
    67.        networkView.RPC("Chat", RPCMode.All, (playerName + ": " + myMessage));
    68.      }
    69.    }
    70.  
    71.    if (toggleMenu)
    72.    {
    73.      if(GUI.Button(Rect(btnX, btnY * 3.4 + btnH, btnW, btnH), "Options"))
    74.      {
    75.        Debug.Log("Loading options...");
    76.        optionsMenu = true;
    77.        toggleMenu = false;
    78.      }
    79.  
    80.      if(GUI.Button(Rect(btnX, btnY * 5.6 + btnH, btnW, btnH), "Exit"))
    81.      {
    82.        Debug.Log("Closing game...");
    83.        exitGame();
    84.      }
    85.    }
    86.  
    87.    if (optionsMenu)
    88.    {
    89.      GUI.Label(Rect(btnX, btnY - 10,150,40), "Mouse Sensitivity");
    90.      ML.sensitivityX = ML.sensitivityY = GUI.HorizontalSlider(new Rect(btnX, btnY,200,50), ML.sensitivityX, 1, 20);
    91.  
    92.      if(GUI.Button(Rect(btnX, btnY * 5.6 + btnH, btnW, btnH), "Return"))
    93.      {
    94.        Debug.Log("Returning to main menu...");
    95.        optionsMenu = false;
    96.        toggleMenu = true;
    97.      }
    98.    }
    99.  
    100. }
    The GUI.Label "Mouse Sensitivity" shows up, but not the slider. This is the error that happens when it tries to create it:

    Code (csharp):
    1. NullReferenceException: Object reference not set to an instance of an object
    2. GameManager.OnGUI () (at Assets/scripts/GameManager.js:225)
    Edit: When I create a new project and follow the instructions in the script you gave me it works fine.

    Edit 2: Ah, I dragged the player prefab into the ML box in the Unity editor and it's working now. I wonder why I needed to do that. Although it changes the sensitivity, it doesn't update it until I close the game and go back in. It's only changing the prefab rather than the instance.
     
    Last edited: Sep 16, 2014
  12. sirhotalot

    sirhotalot

    Joined:
    Sep 9, 2014
    Posts:
    9
    I modified the code in an attempt to have it modify the instance rather than the prefab:

    Code (csharp):
    1. function spawnPlayer()
    2. {
    3.    var playerInstance = Network.Instantiate(playerPrefab, spawnObject.position, Quaternion.identity, 0);
    4.    var ML = playerInstance.gameObject.GetComponent(MouseLook);
    5.    Debug.Log( "Player Instance: " + playerInstance);
    6. }
    Code (csharp):
    1. ML.sensitivityX = ML.sensitivityY = GUI.HorizontalSlider(new Rect(btnX, btnY + 20,200,50), ML.sensitivityX, 1, 10);
    Didn't work, still just modifies the prefab. According to the log it is actually accessing the instance:

    Code (csharp):
    1. MouseLook: FPC(Clone) (MouseLook)
    2. UnityEngine.Debug:Log(Object)
    3. NetworkManager:spawnPlayer() (at Assets/scripts/NetworkManager.js:74)
    4. NetworkManager:OnServerInitialized() (at Assets/scripts/NetworkManager.js:82)
    5. UnityEngine.Network:InitializeServer(Int32, Int32, Boolean)
    6. NetworkManager:startServer() (at Assets/scripts/NetworkManager.js:57)
    7. NetworkManager:OnGUI() (at Assets/scripts/NetworkManager.js:157)
     
    Last edited: Sep 16, 2014
  13. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,501
    Not sure what else to suggest. You might have to just resort to divide-and-conquer: start with the known-working script above, or start with your script, and either add or remove lines to bring one "towards" the other until things stop working, then see what you added that caused the problem.

    Edit: also: if you cannot drop that known good into your project and have it work, then the problem may lie elsewhere in your project's code.

    Kurt