Load font by script

Hi! so this is my problem:

I have this xml files where I’m retrieving data which let me know where to put some texts inside a canvas which I create on the fly with a script both in editor and in runtime if required.

Thing is, if I add the font type from the resources, then the following error is output:

NullReferenceException
UnityEngine.TextGenerator.Populate_Internal_cpp (System.String str, UnityEngine.Font font, Color color, Int32 fontSize, Single scaleFactor, Single lineSpacing, FontStyle style, Boolean richText, Boolean resizeTextForBestFit, Int32 resizeTextMinSize, Int32 resizeTextMaxSize, Int32 verticalOverFlow, Int32 horizontalOverflow, Boolean updateBounds, TextAnchor anchor, Single extentsX, Single extentsY, Single pivotX, Single pivotY, Boolean generateOutOfBounds, Boolean alignByGeometry, System.UInt32& error) (at C:/buildslave/unity/build/artifacts/generated/common/modules/TextRendering/TextRenderingBindings.gen.cs:690)
UnityEngine.TextGenerator.Populate_Internal (System.String str, UnityEngine.Font font, Color color, Int32 fontSize, Single scaleFactor, Single lineSpacing, FontStyle style, Boolean richText, Boolean resizeTextForBestFit, Int32 resizeTextMinSize, Int32 resizeTextMaxSize, VerticalWrapMode verticalOverFlow, HorizontalWrapMode horizontalOverflow, Boolean updateBounds, TextAnchor anchor, Vector2 extents, Vector2 pivot, Boolean generateOutOfBounds, Boolean alignByGeometry, UnityEngine.TextGenerationError& error) (at C:/buildslave/unity/build/artifacts/generated/common/modules/TextRendering/TextRenderingBindings.gen.cs:671)
UnityEngine.TextGenerator.PopulateAlways (System.String str, TextGenerationSettings settings) (at C:/buildslave/unity/build/Runtime/TextRendering/Managed/TextGenerator.cs:265)
UnityEngine.TextGenerator.PopulateWithError (System.String str, TextGenerationSettings settings) (at C:/buildslave/unity/build/Runtime/TextRendering/Managed/TextGenerator.cs:249)
UnityEngine.TextGenerator.Populate (System.String str, TextGenerationSettings settings) (at C:/buildslave/unity/build/Runtime/TextRendering/Managed/TextGenerator.cs:240)
UnityEngine.TextGenerator.GetPreferredWidth (System.String str, TextGenerationSettings settings) (at C:/buildslave/unity/build/Runtime/TextRendering/Managed/TextGenerator.cs:212)
UnityEngine.UI.Text.get_preferredWidth () (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Text.cs:506)
UnityEditor.Events.LayoutPropertiesPreview.<OnPreviewGUI>m__2 (ILayoutElement e) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEditor.UI/UI/LayoutPropertiesPreview.cs:96)
UnityEngine.UI.LayoutUtility.GetLayoutProperty (UnityEngine.RectTransform rect, System.Func`2 property, Single defaultValue, ILayoutElement& source) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Layout/LayoutUtility.cs:86)
UnityEditor.Events.LayoutPropertiesPreview.OnPreviewGUI (Rect r, UnityEngine.GUIStyle background) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEditor.UI/UI/LayoutPropertiesPreview.cs:96)
UnityEditor.ObjectPreview.OnInteractivePreviewGUI (Rect r, UnityEngine.GUIStyle background) (at C:/buildslave/unity/build/Editor/Mono/Inspector/Editor.cs:113)
UnityEditor.ObjectPreview.DrawPreview (IPreviewable defaultPreview, Rect previewArea, UnityEngine.Object[] targets) (at C:/buildslave/unity/build/Editor/Mono/Inspector/Editor.cs:225)
UnityEditor.ObjectPreview.DrawPreview (Rect previewArea) (at C:/buildslave/unity/build/Editor/Mono/Inspector/Editor.cs:128)
UnityEditor.InspectorWindow.DrawPreviewAndLabels () (at C:/buildslave/unity/build/Editor/Mono/Inspector/InspectorWindow.cs:765)
UnityEditor.InspectorWindow.OnGUI () (at C:/buildslave/unity/build/Editor/Mono/Inspector/InspectorWindow.cs:392)
System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) (at /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Reflection/MonoMethod.cs:222)

This is the code that generates this error:

//Creo un text bajo el canvas
                        //GameObject pTextObject = Resources.Load<GameObject>(PREFABS_PATH + "DefaultTextItem");
                        GameObject pTextObject = new GameObject();
                        Text pText = pTextObject.AddComponent<Text>();

                        pTextObject.name = sName;

                        //Añado el font - ERROR HERE
                        pText.font = Resources.Load<Font>(FONTS_PATH + sFont + FONTS_EXT_TTF);

                        //Hago el texto blanco por defecto
                        pText.color = Color.white;

                        pEntity.GetComponent<BackgroundEntity>().addTextElement(pTextObject);

                        showFeedback("Encuentro un font: " + sFont);

What have I seen by now:

  • This is a Unity problem, you should create a prefab with the text component so you just instantiate it and avoid it.

Which I can’t since the game objects I’m creating are meant to be children of another game object and prefabs don’t let that.

How to bypass this

If I can’t get any answer on how to solve this, my best shot will be trying to load the fonts some time later during gameplay (which I still don’t know if it will work)

Any thoughts? (:

If you still need a solution to this: I just had the same issue. I fixed it by Creating a new font after adding the text component to the GameObject.
Text.font = new Font();
This works in most cases of a null Refference Exception.

You can try this:

                     // the font name must be a valid font installed on the system
                     string font_name = "arial" + ".ttf";

                     pText.font = Font.CreateDynamicFontFromOSFont(font_name, 16);`

,You can try this:

                     // the font name must be from a valid font installed on the system
                     string font_name = "arial" + ".ttf";

                     pText.font = Font.CreateDynamicFontFromOSFont(font_name, 16);`