GetComponent problem

I’ve got the following code:

    using UnityEngine;
    using System.Collections;
    
    public class SpriteManager : MonoBehaviour {

        Mesh mesh;

        void Start () {
            if(GetComponent< MeshFilter >()) {
                print("Attached");
            }
            mesh = GetComponent< MeshFilter >().mesh;
        }
    }

I do get the ‘Attached’ message in the console but it also throws the following error:
NullReferenceException: Object reference not set to an instance of an object
SpriteManager.Start

Any ideas why this error pops up?

move ‘mesh=’ line inside IF block too. it can be executed even if no MeshFilter attached

Like Scroodge said, It’s useless to do a check and then ignoring the result. Also you should use a true boolean expression and not just a reference.

public class SpriteManager : MonoBehaviour
{
    Mesh mesh;
    
    void Start ()
    {
        var MF = GetComponent< MeshFilter >();
        if(MF != null)
        {
            print("Attached");
            mesh = MF.mesh;
        }
    }
}