Hello,
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…
Thanks!