- Home /
Question by
Ramsar · Jul 31, 2012 at 08:06 PM ·
getcomponentmeshfilter
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?
Comment
Best Answer
Answer by ScroodgeM · Jul 31, 2012 at 08:14 PM
move 'mesh=' line inside IF block too. it can be executed even if no MeshFilter attached
Answer by Bunny83 · Jul 31, 2012 at 08:55 PM
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;
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613075000im_/https://answers.unity.com/themes/thub/images/avi.jpg)