Search Unity

"The contextual keyword 'var' may only appear within a local variable declaration"

Discussion in 'Scripting' started by MegaBadger24, May 23, 2015.

  1. MegaBadger24

    MegaBadger24

    Joined:
    May 6, 2015
    Posts:
    9
    Greetings community. I am currently trying to have my first-person character sprint upon pressing the "shift" key, but then I ran into two problems when trying to sort out the script. One, as you can see in the title above, appears on lines 6-9 and the solutions I've seen so far don't seem to relate to what I'm trying to do. The second one, appears on line 13, is "This type or namespace name 'function' could not be found". Is there a possible fix for this? I would like to know so I can conquer it next time!

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Sprint : MonoBehaviour  {
    5.  
    6. var NaturalSpeed = 10;
    7. var tempSpeed = ("float");
    8. var SpeedMultiplier = 1.2;
    9. var moveDirection = Vector3;
    10.  
    11.  
    12.  
    13. function Update()
    14.  
    15. {
    16.     moveDirection = Vector3.zero;
    17.         tempSpeed = NaturalSpeed;
    18.  
    19.  
    20.     moveDirection.x += Input.GetAxis("Horizontal");
    21.     moveDirection.z += Input.GetAxis("Vertical");
    22.  
    23.         if(Input.GetKey(KeyCode.LeftShift))
    24.         tempSpeed *= SpeedMultiplier;
    25.         {
    26.             transform.Translate(moveDirection.normalized * tempSpeed * Time.deltaTime); }
    27.  
    28.          }
    29. }
     
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    You're trying to use a weird mix of Unityscript and C#. You can only use one or the other; if you want to write C# you have to use C# syntax only (and vice versa).

    --Eric
     
    krougeau and Kiwasi like this.
  3. krougeau

    krougeau

    Joined:
    Jul 1, 2012
    Posts:
    455
    Just to illustrate Eric's answer, try something like this intead...
    Code (CSharp):
    1. public float NaturalSpeed = 10.0f; // you need to put the "f" after any floating point numbers in C#
    2. public float tempSpeed = 0.0f; // value set at 0 to start, since you're setting it up through code elsewhere
    3. public float  SpeedMultiplier = 1.2f;
    4. public Vector3 moveDirection;
    C# is much less forgiving than JS / UnityScript, which is part of why I like it so much, haha. You have to specifically declare the types of the variables when you set them up.
     
  4. passerbycmc

    passerbycmc

    Joined:
    Feb 12, 2015
    Posts:
    1,741
    @krougeau that is true but in methods you can still use the implicit var way of defineing variables. Though most people prefer explicit types.

    He was mixing syntax since he was trying to use function instead of void to define a method.
     
    krougeau likes this.
  5. MegaBadger24

    MegaBadger24

    Joined:
    May 6, 2015
    Posts:
    9
    Yeah, I might have to switch to that method since I'm new to this. It sucks that lack of knowledge on scripting is what's holding my demo back, since I'm very proud of my design and planning :p I did as you asked and came up with new errors, "Error CS0029: Cannot implicitly convert type 'int' to 'string' (CS0029) (Assembly-CSharp)" and 49,49): Error CS1061: 'UnityEngine.Vector3' does not contain a definition for 'tempSpeed' and no extension method 'tempSpeed' accepting a first argument of type 'UnityEngine.Vector3' could be found (are you missing a using directive or an assembly reference?) (CS1061) (Assembly-CSharp)

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Sprint : MonoBehaviour  {
    5.  
    6. //public int NaturalSpeed = 10.0f;
    7. public string tempSpeed = 0.0f;
    8. public float SpeedMultiplier = 1.2f;
    9. public Vector3 moveDirection;
    10.  
    11. void Update()
    12.  
    13. {
    14.     moveDirection = Vector3.zero;
    15.         tempSpeed = NaturalSpeed;
    16.    
    17.  
    18.     moveDirection.x += Input.GetAxis("Horizontal");
    19.     moveDirection.z += Input.GetAxis("Vertical");
    20.    
    21.         if(Input.GetKey(KeyCode.LeftShift))
    22.         tempSpeed = SpeedMultiplier;
    23.         {
    24.             transform.Translate(moveDirection.normalized.tempSpeed = Time.deltaTime); }
    25.  
    26.          }
    27. }
     
  6. RiokuTheSlayer

    RiokuTheSlayer

    Joined:
    Aug 22, 2013
    Posts:
    356
    You're setting tempSpeed to the type string, but then trying to use it as a float. Change line 7 to be "public float tempSpeed = 0.0f;"

    Also, the other error is you trying to use moveDirection.normalized.tempSpeed at line 24. I don't knoe why you're doing that, but you need to remove .tempSpeed or change . to something like +, -, *, ect.
     
  7. MegaBadger24

    MegaBadger24

    Joined:
    May 6, 2015
    Posts:
    9
    I had a prior error where "=*" was an invalid meaning.
     
  8. RiokuTheSlayer

    RiokuTheSlayer

    Joined:
    Aug 22, 2013
    Posts:
    356
    *=, not =*
     
  9. krougeau

    krougeau

    Joined:
    Jul 1, 2012
    Posts:
    455
    In retrospect, I should have converted the entire script for the OP. It was late, I was tired :p
     
  10. MegaBadger24

    MegaBadger24

    Joined:
    May 6, 2015
    Posts:
    9
    Code (CSharp):
    1.         {
    2.             transform.Translate(moveDirection + tempSpeed = Time.deltaTime); }
    3.  
    4.          }
    5. }
    I guess so, that will change now! I'm slowly learning :p

    Here's the last problem that I haven't found a fix for regarding sprint: "Operator '+' cannot be applied to operands of type 'UnityEngine.Vector3' and 'float'"

    Then I've got to figure out crouching, throwing and object animations. I'm presenting a demo this Wednesday :p
     
  11. krougeau

    krougeau

    Joined:
    Jul 1, 2012
    Posts:
    455
    A couple of things... First, you I don't think you want those values to = Time.deltaTime, but to be multiplied by Time.deltaTime... Change = to *...

    The error you're receiving is pretty self explanatory... You can't add a Vector3 to a float, so instead, you'd want to add tempSpeed to one or more of the Vector3 float values (x, y or z).

    As an example, the following would / should move your object on the X axis by a factor of tempSpeed multiplied by Time.deltaTime:
    Code (CSharp):
    1. transform.Translate(moveDirection.x + tempSpeed * Time.deltaTime, moveDirection.y, moveDirection.z);
     
  12. MegaBadger24

    MegaBadger24

    Joined:
    May 6, 2015
    Posts:
    9
    So I found out that the sprint script doesn't actually work for my character, despite after everything was fixed up.. So would applying the sprint script to the FPC script work out?


    Code (JavaScript):
    1. //////////////////////////////////////////////////////////////
    2. // FirstPersonControl.js
    3. //
    4. // FirstPersonControl creates a control scheme where the camera
    5. // location and controls directly map to being in the first person.
    6. // The left pad is used to move the character, and the
    7. // right pad is used to rotate the character. A quick double-tap
    8. // on the right joystick will make the character jump.
    9. //
    10. // If no right pad is assigned, then tilt is used for rotation
    11. // you double tap the left pad to jump
    12. //////////////////////////////////////////////////////////////
    13.  
    14. #pragma strict
    15.  
    16. @script RequireComponent( CharacterController )
    17.  
    18. // This script must be attached to a GameObject that has a CharacterController
    19. var moveTouchPad : Joystick;
    20. var rotateTouchPad : Joystick;                        // If unassigned, tilt is used
    21.  
    22. var cameraPivot : Transform;                        // The transform used for camera rotation
    23.  
    24. var forwardSpeed : float = 4;
    25. var backwardSpeed : float = 1;
    26. var sidestepSpeed : float = 1;
    27. var jumpSpeed : float = 8;
    28. var inAirMultiplier : float = 0.25;                    // Limiter for ground speed while jumping
    29. var rotationSpeed : Vector2 = Vector2( 50, 25 );    // Camera rotation speed for each axis
    30. var tiltPositiveYAxis = 0.6;
    31. var tiltNegativeYAxis = 0.4;
    32. var tiltXAxisMinimum = 0.1;
    33. var Sprint : MonoBehaviour  {
    34.  
    35. var float NaturalSpeed = 10.0f;
    36. var float tempSpeed = 0.0f;
    37. var float SpeedMultiplier = 1.2f;
    38. var Vector3 moveDirection;
    39. var float FirstPersonControl;
    40.  
    41. private var thisTransform : Transform;           },
    42. private var character : CharacterController;
    43. private var cameraVelocity : Vector3;
    44. private var velocity : Vector3;                        // Used for continuing momentum while in air
    45. private var canJump = true;
    46.  
    47. function Start()
    48. {
    49.     // Cache component lookup at startup instead of doing this every frame      
    50.     thisTransform = GetComponent( Transform );
    51.     character = GetComponent( CharacterController );  
    52.  
    53.     // Move the character to the correct start position in the level, if one exists
    54.     var spawn = GameObject.Find( "PlayerSpawn" );
    55.     if ( spawn )
    56.         thisTransform.position = spawn.transform.position;
    57. }
    58.  
    59. function OnEndGame()
    60. {
    61.     // Disable joystick when the game ends  
    62.     moveTouchPad.Disable();
    63.  
    64.     if ( rotateTouchPad )
    65.         rotateTouchPad.Disable();  
    66.  
    67.     // Don't allow any more control changes when the game ends
    68.     this.enabled = false;
    69. }
    70.  
    71. function Update()
    72. {
    73.     var movement = thisTransform.TransformDirection( Vector3( moveTouchPad.position.x, 0, moveTouchPad.position.y ) );
    74.  
    75.     // We only want horizontal movement
    76.     movement.y = 0;
    77.     movement.Normalize();
    78.  
    79.     // Apply movement from move joystick
    80.     var absJoyPos = Vector2( Mathf.Abs( moveTouchPad.position.x ), Mathf.Abs( moveTouchPad.position.y ) );  
    81.     if ( absJoyPos.y > absJoyPos.x )
    82.     {
    83.         if ( moveTouchPad.position.y > 0 )
    84.             movement *= forwardSpeed * absJoyPos.y;
    85.         else
    86.             movement *= backwardSpeed * absJoyPos.y;
    87.     }
    88.     else
    89.         movement *= sidestepSpeed * absJoyPos.x;      
    90.  
    91.     // Check for jump
    92.     if ( character.isGrounded )
    93.     {      
    94.         var jump = false;
    95.         var touchPad : Joystick;
    96.         if ( rotateTouchPad )
    97.             touchPad = rotateTouchPad;
    98.         else
    99.             touchPad = moveTouchPad;
    100.  
    101.         if ( !touchPad.IsFingerDown() )
    102.             canJump = true;
    103.      
    104.          if ( canJump && touchPad.tapCount >= 2 )
    105.          {
    106.             jump = true;
    107.             canJump = false;
    108.          }  
    109.      
    110.         if ( jump )
    111.         {
    112.             // Apply the current movement to launch velocity      
    113.             velocity = character.velocity;
    114.             velocity.y = jumpSpeed;  
    115.         }
    116.     }
    117.     else
    118.     {          
    119.         // Apply gravity to our velocity to diminish it over time
    120.         velocity.y += Physics.gravity.y * Time.deltaTime;
    121.              
    122.         // Adjust additional movement while in-air
    123.         movement.x *= inAirMultiplier;
    124.         movement.z *= inAirMultiplier;
    125.     }
    126.      
    127.     movement += velocity;  
    128.     movement += Physics.gravity;
    129.     movement *= Time.deltaTime;
    130.  
    131.     // Actually move the character  
    132.     character.Move( movement );
    133.  
    134.     if ( character.isGrounded )
    135.         // Remove any persistent velocity after landing  
    136.         velocity = Vector3.zero;
    137.  
    138.     // Apply rotation from rotation joystick
    139.     if ( character.isGrounded )
    140.     {
    141.         var camRotation = Vector2.zero;
    142.      
    143.         if ( rotateTouchPad )
    144.             camRotation = rotateTouchPad.position;
    145.         else
    146.         {
    147.             // Use tilt instead
    148. //            print( iPhoneInput.acceleration );
    149.             var acceleration = Input.acceleration;
    150.             var absTiltX = Mathf.Abs( acceleration.x );
    151.             if ( acceleration.z < 0 && acceleration.x < 0 )
    152.             {
    153.                 if ( absTiltX >= tiltPositiveYAxis )
    154.                     camRotation.y = (absTiltX - tiltPositiveYAxis) / (1 - tiltPositiveYAxis);
    155.                 else if ( absTiltX <= tiltNegativeYAxis )
    156.                     camRotation.y = -( tiltNegativeYAxis - absTiltX) / tiltNegativeYAxis;
    157.             }
    158.          
    159.             if ( Mathf.Abs( acceleration.y ) >= tiltXAxisMinimum )
    160.                 camRotation.x = -(acceleration.y - tiltXAxisMinimum) / (1 - tiltXAxisMinimum);
    161.         }
    162.      
    163.         camRotation.x *= rotationSpeed.x;
    164.         camRotation.y *= rotationSpeed.y;
    165.         camRotation *= Time.deltaTime;
    166.      
    167.         // Rotate the character around world-y using x-axis of joystick
    168.         thisTransform.Rotate( 0, camRotation.x, 0, Space.World );
    169.      
    170.         // Rotate only the camera with y-axis input
    171.         cameraPivot.Rotate( -camRotation.y, 0, 0 );
    172.     }
    173.  
    174. function Update()
    175. {
    176.     moveDirection = Vector3.zero;
    177.         tempSpeed = NaturalSpeed;
    178.  
    179.  
    180.     moveDirection.x += Input.GetAxis("Horizontal");
    181.     moveDirection.z += Input.GetAxis("Vertical");
    182.  
    183.         if(Input.GetKey("LeftShift"))
    184.         tempSpeed = SpeedMultiplier;
    185.         {
    186.             transform.Translate(moveDirection.x + tempSpeed * Time.deltaTime, moveDirection.y, moveDirection.z); }
    187.  
    188.          }
    189. }