x


error with instance of TerrainData?

I have this code:

var terrain : Terrain;
function FixedUpdate()
{
    if (Input.GetButton ("Crouch"))
    {
        if (transform.position.y > terrain.terrainData.GetHeight(transform.position.x, transform.position.y))
        {
            transform.position.y =transform.position.y - transform.position.y/50;
        }
    }
}

And I'm getting this error:

"NullReferenceException: Object reference not set to an instance of an object Commander.FixedUpdate ()"

the error comes up when I press crouch and points to the 2nd if statement line.

can anyone help me resolve this error?

more ▼

asked Mar 19 '11 at 10:37 PM

Jordan Miller 2 gravatar image

Jordan Miller 2
348 47 51 57

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

Drag your terrain into the terrain slot in the inspector. terrain is just a var name, and isn't auto-hooked up to anything, even though is looks like it is.

BUT, you probably want this instead (and can lose the terrain var):

Terrain.activeTerrain.terrainData
more ▼

answered Mar 20 '11 at 03:56 AM

Owen Reynolds gravatar image

Owen Reynolds
11.3k 1 7 45

Thanks Much! I just used your code, but there is only one problem - for some reason it always returns a value around 65 and I have a very uneven terrain, so I don't know what I'm doing wrong but I've found a way working around this whole piece of code so i guess it doesn't matter. thanks though, I'll use this later I'm sure.

Mar 20 '11 at 05:09 PM Jordan Miller 2

Opps! Unity uses x and Z for the ground. You used x and y in GetHeight (which would be correct for 3DSMax, blender, etc... .)

Mar 20 '11 at 06:03 PM Owen Reynolds
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x1472
x48
x6

asked: Mar 19 '11 at 10:37 PM

Seen: 933 times

Last Updated: Mar 19 '11 at 10:37 PM