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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

C# version of JavaScript code

Discussion in 'Scripting' started by Ap0C552, Feb 15, 2015.

  1. Ap0C552

    Ap0C552

    Joined:
    Feb 7, 2015
    Posts:
    43
    I am attempting to issue a move command to a navmeshagent.

    For some reason in the docs the example is in JavaScript, and my C# equivalent is giving me an error.

    this is the example code in the docs....

    Code (CSharp):
    1. / Script to move a NavMeshAgent to the place where
    2. // the mouse is clicked.
    3.     private var agent: NavMeshAgent;
    4.  
    5.     function Start () {
    6.         agent = GetComponent.<NavMeshAgent>();
    7.     }
    8.  
    9.     function Update () {
    10.         var hit: RaycastHit;
    11.  
    12.         // When the mouse is clicked...
    13.         if (Input.GetMouseButtonDown(0)) {
    14.             // If the click was on an object then set the agent's
    15.             // destination to the point where the click occurred.
    16.             var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    17.        
    18.             if (Physics.Raycast(ray, hit)) {
    19.                 agent.SetDestination(hit.point);
    20.             }
    21.         }
    22.     }

    Here is what I am doing in C#

    Code (CSharp):
    1.  navagent.SetDestination(end);
    2.         RaycastHit hit;
    3.         // If the click was on an object then set the agent's
    4.         // destination to the point where the click occurred.
    5.         Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    6.  
    7.         if (Physics.Raycast(ray, hit)) { // error line
    8.             navagent.SetDestination(hit.point);
    9.         }
    It is giving me the error that...

     
  2. DanielQuick

    DanielQuick

    Joined:
    Dec 31, 2010
    Posts:
    3,137
    Code (csharp):
    1. if(Physics.Raycast(ray, out hit)){
    Notice the added 'out'
     
  3. SteveJ

    SteveJ

    Joined:
    Mar 26, 2010
    Posts:
    3,066
    Code (csharp):
    1.  
    2. if (Physics.Raycast(ray, out hit))
    3.  
     
  4. Ap0C552

    Ap0C552

    Joined:
    Feb 7, 2015
    Posts:
    43
    Thanks for the reply. I am a c++ and Java programmer. I have never heard of the out keyword. I will have to look it up.
     
  5. hpjohn

    hpjohn

    Joined:
    Aug 14, 2012
    Posts:
    2,190
    OP, the docs have c# examples, click the button in the top right