SpriteRenderer.enabled = false crashes project
Hello everyone. Making a turn-based strategy game. #30 string in HexPoint class' constructor get NullReferenceException: Object reference not set to an instance of an object I disabled this object in Unity, but now when this string (HexInfo.enabled = false;) is commented project crushes. Having no idea why. [Project][1] [1]: /storage/temp/64107-scripts.zip
Answer by EmHuynh · Feb 17, 2016 at 06:34 PM
Hello, @Kelborn.
In HexPoint's constructor:
public HexPoint()
{
// ...
HexInfo = GetComponent<MeshRenderer> ();
// ...
HexInfo.enabled = false;
// ...
}
The NullReferenceException
error is caused by the failure to initialize`HexInfo` by calling GetComponent< MeshRender >()
. This is because there isn't a MeshRender component attached to the game object of HexPoint component.
To fix this error, attach a MeshRender component to the game object that has the HexPoint component.
Call GameObject.SetActive
to activate or deactivate a game object. Here is the documentation: http://docs.unity3d.com/ScriptReference/GameObject.SetActive.html
Right. $$anonymous$$y mesh is in child :D Stupid mistake. Thanks. BTW, what's the difference between .enabled and SetActive? SetActive is for gameobjects and .enabled is for components, right?
@$$anonymous$$elborn, No problem! And yes, if they are derived from $$anonymous$$onoBehaviour, you can disable it: GetComponent< SomeCSScript >().enabled = false;