MissingReferenceException: The object of type 'Material' has been destroyed but you are still trying

hello everybody,
I wrote a script for player’s movement as always but this time I confront an error which I suppose is related to my terrain. here is the script that have error:

Please post code as text and enclose it in code tags.

If the highlighted line is where the error is, then m_PreviewMaterial has lost its internal reference to the C++ object (it is not null). This can happen when calling Destroy() but still accessing the object within the same frame.

It’s best to avoid the situation by hunting down the root cause. Typically, you will want to do null the reference whenever you destroy it:

Destroy(m_PreviewMaterial);
m_PreviewMaterial = null;

If the reference is in another script you can use events to notify of the reference being destroyed.

But it’s not always a manageable solution for editor scripts. In that case you can extend the null check like this:

if (m_PreviewMaterial == null || System.Object.ReferenceEquals(m_PreviewMaterial, null))
{
    // ....
}

The answer is always the same… ALWAYS!

How to fix a NullReferenceException error

https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

Three steps to success:

  • Identify what is null ← any other action taken before this step is WASTED TIME
  • Identify why it is null
  • Fix that