Search Unity

how to use "Raycast" in c#?

Discussion in 'Scripting' started by Viskag, Apr 21, 2009.

  1. Viskag

    Viskag

    Joined:
    Apr 20, 2009
    Posts:
    46
    in javascript it can work with:
    Code (csharp):
    1.  
    2. var myhit : RaycastHit;
    3. var myray : Ray;
    4. function Update ()
    5. {
    6.     myray = Camera.main.ScreenPointToRay (Input.mousePosition);
    7.     if( Physics.Raycast(myray, myhit, 1000.0)  Input.GetMouseButtonDown(0) )
    8.         print(myhit.collider.name);
    9. }
    10.  
    but below doesn't work with "error CS1502: The best overloaded method match for `UnityEngine.Physics.Raycast(UnityEngine.Vector3, UnityEngine.Vector3, float)' has some invalid arguments":
    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4. public class hitcs : MonoBehaviour
    5. {
    6.     RaycastHit myhit = new RaycastHit();
    7.     Ray myray = new Ray();
    8.     void Update()
    9.     {
    10.         myray = Camera.main.ScreenPointToRay(Input.mousePosition);
    11.         if (Physics.Raycast(myray, myhit, 1000.0f)  Input.GetMouseButtonDown(0))
    12.             print(myhit.collider.name);
    13.     }
    14. }
    15.  
    what did i miss??thx!i can't find unity manual for c#...
     
  2. remz

    remz

    Joined:
    Apr 21, 2009
    Posts:
    16
    short : you need to add the "out" keyword before your RaycastHit parameter.

    long :
    the trick here is the keyword "out" in the method's signature in c#.


    as HitInfo is actually a c# struct and not a class, the default behavior when passing it to a method is to pass it by value instead of by reference. but in this case the method Raycast needs to modify the RaycastHit instance for you. that's why the signature of the method has a little "out" word, to specify that the structure must be passed by reference.

    hope it makes sense!

    oh and hello unity forum, this is my first post
    :)
     
    Jawad2Heaven likes this.
  3. Viskag

    Viskag

    Joined:
    Apr 20, 2009
    Posts:
    46
    thx!and this is my third post.
     
  4. Viskag

    Viskag

    Joined:
    Apr 20, 2009
    Posts:
    46
    hoho,it works!just add a "out" before "myhit".
     
  5. hungrytom

    hungrytom

    Joined:
    Sep 23, 2009
    Posts:
    34
    Thanks. Useful info!
     
  6. stephane

    stephane

    Joined:
    Feb 17, 2010
    Posts:
    7
  7. andeeeee

    andeeeee

    Joined:
    Jul 19, 2005
    Posts:
    8,768
    This has been noted for a forthcoming update of the docs.
     
  8. TheGrimDerp

    TheGrimDerp

    Joined:
    Dec 8, 2012
    Posts:
    6
    :confused:This is my
    Code (csharp):
    1. ~~first post as well.~~
    ~ second post. Thank you very much for helping this finally make sense and work.
     
    Last edited: Feb 11, 2014