Search Unity

  1. New Unity Live Help updates. Check them out here!

    Dismiss Notice

Need help with small bug...

Discussion in 'Editor & General Support' started by Jason210, Mar 29, 2013.

  1. Jason210

    Jason210

    Joined:
    Oct 14, 2012
    Posts:
    127
    Hi

    I'm learning C# at the same time as Unity so it's a bit of an uphill struggle as most examples are in Javascript. Anyway, I wanted to make a script that can tell me the name of the object I'm walking on. The script is attached to the first person camera.

    The following code works, but if the ray doesn't intersect the floor, for example when I jump, it gives an error. All I need to do is stop that error. I can't stop it by making the ray longer because there are things on the next floor that it could touch. The ray needs to be the length it is.


    using UnityEngine;
    using System.Collections;

    public class GetSectionName : MonoBehaviour {

    void Update () {

    Vector3 dwn = transform.TransformDirection(0,-1,0);

    RaycastHit hit = new RaycastHit();

    if (Physics.Raycast(transform.position, dwn, out hit, 2)); {

    print (hit.collider.name);
    }

    }
    }


    What I need is way to deal with the NullReferenceException: Object reference not set to an instance of an object
     
  2. WheresMommy

    WheresMommy

    Joined:
    Oct 4, 2012
    Posts:
    888
    Dont know if this fixes your code, but is the ";" right after the if function right? As far as I know, C# isnt different to Javascript in this case. Maybe that is something where Unity gets confused?
     
  3. Jason210

    Jason210

    Joined:
    Oct 14, 2012
    Posts:
    127
    Yes, oddly enough that was the cause. Strange the editor didn't pick it up and that I could compile. Anyway, now this is fixed what happens is what I expected to happen!

    Thanks.
     
  4. Kragh

    Kragh

    Joined:
    Jan 22, 2008
    Posts:
    638
    Well, there's nothing wrong with writing the ";" after the if statement. It just means the end of the if statement. Your line just says "if something, then...nothing". And then you define a new scope: Print something. And this print is done always, whether or not the if statement reads as true or not. The two are seperated by you ";" So it will compile fine, but you will try and print stuff, even if your hit.collider is null.
     
  5. Jason210

    Jason210

    Joined:
    Oct 14, 2012
    Posts:
    127
    Yup! Thanks for clarifying that further. It's good to know the logic behind bugs...
     
unityunity