Why is this simple code giving errors?

Hello!

I’m very new to Unity and C# so I’m sorry to ask a dumb question, but I’ve done some research and I can’t make sense of this by myself.

I have a very simple scene with a capsule sitting above a plane. I need the capsule’s rotation to match that of the plane - but at runtime. I put this script in the capsule.

using UnityEngine;
using System.Collections;

public class testmove : MonoBehaviour
{
    void FixedUpdate()
    {
        RaycastHit ground = new RaycastHit();
        Physics.Raycast (transform.position, transform.forward, out ground);
        transform.rotation = ground.transform.rotation;
    }
}

This script works perfectly, the capsule snaps to the rotation of its “floor”. Yet, even though the script works, it throws errors at the same time. Every time FixedUpdate is called, a NullReferenceException is thrown telling me there’s an error on line 10.

Why is it giving me errors even though it’s working? How do I fix it?

You should only attempt to access ground.transform if the raycast returns true. If it’s false then it will be null.

–Eric

Oh wow. I didn’t realize it was debugging hypothetical situations. Thanks for the help!

It’s not doing that; code doesn’t run hypothetical situations, only what’s actually happening. You’re simply attempting to refer to ground.transform even in those cases when it’s null. You have to check if the raycast returned true because that’s the only way you know that the ground variable has valid data. Or you could check whether ground.transform is null, but it would be cleaner to just check the raycast.

–Eric

Yeah you’re right. What happened is after the capsule rotated, it was just under the ground that I thought it was above, or something like that. And then I got confused and thought the debugger was super smart. But I get it now. Thanks!