Error when adding a UI Text component to a gameobject?

Hi! I am making a stacking system so the player can stack items. But. When i add a UI Text component to show how many items are on that stack. I get an error. Here’s my script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class inventoryScript : MonoBehaviour {






	GameObject[] slotContentsGo = new GameObject[inventorySlotsCount];
	public static int inventorySlotsCount = 52;
	public static Items[] slotContents = new Items[inventorySlotsCount];
	public GameObject[] inventorySlotsAr = new GameObject[inventorySlotsCount];

	void Start() {
		getSlots ();
	}

	static void hideInventory() {
		GameObject inventory = GameObject.Find ("Inventory");
		for (int i = 0; i < inventory.transform.childCount; i++) {
			inventory.transform.GetChild (i).gameObject.SetActive (!inventory.transform.GetChild (i).gameObject.activeInHierarchy);
		}
	}

	public void takeItem(Items itemToTake) {
			for (int i = 0; i < slotContents.Length; i++) {
			if (itemToTake == slotContents  *&& itemToTake != null) {*

_ slotContents = null;_
_ Destroy (slotContentsGo*);
break;
}
}
}*_

* public void clearInventory() {*
* for (int i = 0; i < inventorySlotsCount; i++) {*
_ slotContents = null;
Destroy (slotContentsGo );
* }
}
public void removeAtSlot(int slot) {
for (int i = 0; i < slotContents.Length; i++) {
if (i == slot) {
if (slotContents [slot] != null) {
slotContents = null;
Destroy (slotContentsGo );
}
}
}
}*_

public void addItem(Items itemToAdd) {
* for (int i = 0; i < slotContents.Length; i++) {*
_ if (slotContents == null && itemToAdd != null && itemToAdd.stackable == false) {
slotContents = itemToAdd;
GameObject returnedItem = createItem (itemToAdd.itemSprite, inventorySlotsAr .gameObject.transform, itemToAdd.itemName);
slotContentsGo = returnedItem;
* break;
}
}
}*_

// Relevant bit
* public GameObject createItem(Sprite imageSprite, Transform slot, string itemName) {*
// Here i am creating two gameobjects. The item. And the stack text
// But i get an error when i try to add the Text component
* GameObject createObj = new GameObject ();*
* GameObject stackText = new GameObject (itemName + " StackText");*
* createObj.AddComponent ();*
* createObj.GetComponent ().sprite = imageSprite;*
* createObj.transform.position = slot.position;*
* createObj.transform.rotation = slot.rotation;*
* createObj.transform.SetParent (slot.transform);*
* createObj.transform.localScale = new Vector3 (slot.transform.localScale.x, slot.transform.localScale.y);*
* createObj.name = itemName;*
* stackText.transform.SetParent (createObj.transform);*
* stackText.AddComponent ();*
* stackText.transform.position = new Vector3 (slot.transform.position.x, slot.transform.position.y);*
* stackText.transform.localScale = new Vector3 (slot.transform.localScale.x, slot.transform.localScale.y);*
* stackText.AddComponent ();*
* stackText.GetComponent ().fontSize = 45;*
* stackText.GetComponent ().fontStyle = FontStyle.Bold;*
* stackText.GetComponent ().alignment = TextAnchor.LowerLeft;*
* stackText.GetComponent ().color = new Color (0, 0, 0, 255);*
* return createObj;*
* }*

* void getSlots() {*
* for (int i = 0; i < inventorySlotsCount; i++) {*
_ if (inventorySlotsAr == null) {
inventorySlotsAr = GameObject.Find (“inventorySlot (” + i.ToString() + “)”);
* }
if(i == 0) {
inventorySlotsAr = GameObject.Find (“inventorySlot”);
}
}
}*_

}

Edit: This is my error
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.GetPreferredHeight (System.String str, TextGenerationSettings settings) (at C:/buildslave/unity/build/Runtime/TextRendering/Managed/TextGenerator.cs:220)
UnityEngine.UI.Text.get_preferredHeight () (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Text.cs:522)
UnityEditor.Events.LayoutPropertiesPreview.m__3 (ILayoutElement e) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEditor.UI/UI/LayoutPropertiesPreview.cs:97)
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:97)
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)

If you look at the stack trace above, the method UnityEngine.TextGenerator.Populate_Internal_cpp takes an argument called font which is of type UnityEngine.Font. So when you try to add the Text component the font field is going to be initialized to null, which in turn is causing you the null reference exception.

One way to overcome this is to create a prefab of the gameobject with Text component added to it and instantiate a gameobject from this prefab and set the required values on this instantiated prefab.