NullReferenceException with Terrain.activeTerrain


I have been programming in Unity and C# for quite some time now and I have never come to this error before. In short, I am making a prototype for a flight simulator so I have basic movement down, but nothing short of that. The issue in the code has to do with the plane colliding with the terrain, and because of the need to have the plane be kinematic, I cannot use RigidBody and colliders. In turn, I found this line of code…

float terrainHeightAtMyPosition = Terrain.activeTerrain.SampleHeight(transform.position);

… which is part of the whole code that I have which is…

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Threading;
using UnityEngine;

public class PlaneMovement : MonoBehaviour
    public float speed = 100f;

    void Update()
        transform.position += -transform.right * Time.deltaTime * speed;
        transform.Rotate(Input.GetAxis("Horizontal") * 5, 0f, Input.GetAxis("Vertical") * 5);
        speed += transform.right.y * 50.0f * Time.deltaTime;

        float terrainHeightAtMyPosition = Terrain.activeTerrain.SampleHeight(transform.position);
        if (terrainHeightAtMyPosition > transform.position.y)
            transform.position = new Vector3(transform.position.x, terrainHeightAtMyPosition, transform.position.z);

I end up getting this error…

NullReferenceException: Object reference not set to an instance of an object
PlaneMovement.Update () (at Assets/Scripts/PlaneMovement.cs:19)

I cannot pinpoint exactly what the issue is with what I am doing, so hopefully someone can help fix the error.

All of the Terrain parts are the same, so here is one of them…


You may not have an instance of your terrain

I don’t see any terrain here, only meshes with colliders.

Do you have any object with the Terrain component attached? If not, you need one, otherwise Terrain.activeTerrain will return null. After attaching the Terrain component, right click in your Project tab > Create > Terrain and provide the terrain asset to the component.

With the Terrain component & its tools, you will be able to create your actual terrain, and Terrain.activeTerrain will return the terrain you have created.

Ok, so I got that, I initially attached that but it didn’t change anything. Maybe this is why, because it says, “Terrain Asset Missing” and then I am not sure what to do about that part.