MonoBehaviour using the ‘new’ keyword. This is not allowed. MonoBehaviours can only be added using A

I have made this Script:

Start of the Script:

using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UI;
public class CraftingSystem : MonoBehaviour
{
    public GameObject craftingScreenUI;
    public GameObject toolsScreenUI, SurvivalScreenUI, RefineScreenUI, ConstructionScreenUI;
  
    public List<string> inventoryItemList = new List<string>();
    Button toolsBTN, survivalBTN, refineBTN, constructionBTN;
    Button craftAxeBTN, craftPlankBTN, craftFoundationBTN, craftWallBTN;
    Text AxeReq1, AxeReq2, PlankReq1, FoundationReq1, WallReq1;
    public bool isOpen;
  
    public Blueprint AxeBLP = new Blueprint("Axe", 1, 2, "Stone", 2, "Stick", 3); // new muss ersetz werden.
    public Blueprint PlankBLP = new Blueprint("Plank", 2, 1, "Log", 1, "", 0); // new muss ersetz werden.
    public Blueprint FoundationBLP = new Blueprint("Foundation", 1, 1, "Plank", 4, "", 0);// new muss ersetz werden.
    public Blueprint WallBLP = new Blueprint("Wall", 1, 1, "Plank", 5, "", 0);// new muss ersetz werden.
    public static CraftingSystem Instance { get; set; }
    public void Awake()
    {
        if (Instance != null && Instance != this)
        {
            Destroy(gameObject);
        }
        else
        {
            Instance = this;
        }
    }

It shows the Error “You are trying to create a MonoBehaviour using the ‘new’ keyword.
This is not allowed.” What do I have to do now? I know i have to change the for “new” keywords, but I dont know how. Can somebody help me, please?
can only be added using
AddComponent().

Don’t do that because you cannot. It’s not legal.

If you want to do that, still don’t do that.

If you don’t need it to be a MonoBehaviour, remove the inheritance.

If you DO need it to be a MonoBehaviour, use the .AddComponent() method.

Imphenzia: How Did I Learn To Make Games:

Tutorials and example code are great, but keep this in mind to maximize your success and minimize your frustration:

How to do tutorials properly, two (2) simple steps to success:

Step 1. Follow the tutorial and do every single step of the tutorial 100% precisely the way it is shown. Even the slightest deviation (even a single character!) generally ends in disaster. That’s how software engineering works. Every step must be taken, every single letter must be spelled, capitalized, punctuated and spaced (or not spaced) properly, literally NOTHING can be omitted or skipped.
Fortunately this is the easiest part to get right: Be a robot. Don’t make any mistakes.
BE PERFECT IN EVERYTHING YOU DO HERE!!

If you get any errors, learn how to read the error code and fix your error. Google is your friend here. Do NOT continue until you fix your error. Your error will probably be somewhere near the parenthesis numbers (line and character position) in the file. It is almost CERTAINLY your typo causing the error, so look again and fix it.

Step 2. Go back and work through every part of the tutorial again, and this time explain it to your doggie. See how I am doing that in my avatar picture? If you have no dog, explain it to your house plant. If you are unable to explain any part of it, STOP. DO NOT PROCEED. Now go learn how that part works. Read the documentation on the functions involved. Go back to the tutorial and try to figure out WHY they did that. This is the part that takes a LOT of time when you are new. It might take days or weeks to work through a single 5-minute tutorial. Stick with it. You will learn.

Step 2 is the part everybody seems to miss. Without Step 2 you are simply a code-typing monkey and outside of the specific tutorial you did, you will be completely lost. If you want to learn, you MUST do Step 2.

Of course, all this presupposes no errors in the tutorial. For certain tutorial makers (like Unity, Brackeys, Imphenzia, Sebastian Lague) this is usually the case. For some other less-well-known content creators, this is less true. Read the comments on the video: did anyone have issues like you did? If there’s an error, you will NEVER be the first guy to find it.

Beyond that, Step 3, 4, 5 and 6 become easy because you already understand!

Finally, when you have errors, don’t post here… just go fix your errors! Here’s how:

Remember: NOBODY here memorizes error codes. That’s not a thing. The error code is absolutely the least useful part of the error. It serves no purpose at all. Forget the error code. Put it out of your mind.

The complete error message contains everything you need to know to fix the error yourself.

The important parts of the error message are:

  • the description of the error itself (google this; you are NEVER the first one!)
  • the file it occurred in (critical!)
  • the line number and character position (the two numbers in parentheses)
  • also possibly useful is the stack trace (all the lines of text in the lower console window)

Always start with the FIRST error in the console window, as sometimes that error causes or compounds some or all of the subsequent errors. Often the error will be immediately prior to the indicated line, so make sure to check there as well.

Look in the documentation. Every API you attempt to use is probably documented somewhere. Are you using it correctly? Are you spelling it correctly?

All of that information is in the actual error message and you must pay attention to it. Learn how to identify it instantly so you don’t have to stop your progress and fiddle around with the forum.

thank you verry much. Can you pleas show me in my code what I have to do?

Like @Kurt-Dekker said. If any class inherits from MonoBehaviour it can’t have a constructor, if can’t have a constructor you can’t use a new keyword.

Edit: Even if you have a programming background check this materials to wrap your head around Unity concepts.

Can you please show me in my Code, where I have to do it.

You must post what Blueprint is because if the class Blueprint inherits from MonoBehaviour you can’t use a new keyword.

That is the hole script, but i dont know how and where to use .AddComponent<>().
Can you please show it in my Code?
Its in line 28-31

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


public class CraftingSystem : MonoBehaviour
{
    public GameObject craftingScreenUI;
    public GameObject toolsScreenUI, SurvivalScreenUI, RefineScreenUI, ConstructionScreenUI;
   


    public List<string> inventoryItemList = new List<string>();

    Button toolsBTN, survivalBTN, refineBTN, constructionBTN;

    Button craftAxeBTN, craftPlankBTN, craftFoundationBTN, craftWallBTN;

    Text AxeReq1, AxeReq2, PlankReq1, FoundationReq1, WallReq1;

    public bool isOpen;
  
  

    public Blueprint AxeBLP = new Blueprint("Axe", 1, 2, "Stone", 2, "Stick", 3); 
    public Blueprint PlankBLP = new Blueprint("Plank", 2, 1, "Log", 1, "", 0); 
    public Blueprint FoundationBLP = new Blueprint("Foundation", 1, 1, "Plank", 4, "", 0);
    public Blueprint WallBLP = new Blueprint("Wall", 1, 1, "Plank", 5, "", 0);

    public static CraftingSystem Instance { get; set; }

    public void Awake()
    {
        if (Instance != null && Instance != this)
        {
            Destroy(gameObject);

        }
        else
        {
            Instance = this;
        }
    }

    // Start is called before the first frame update
    void Start()
    {
        isOpen = false;

        toolsBTN = craftingScreenUI.transform.Find("ToolsButton").GetComponent<Button>();
        toolsBTN.onClick.AddListener(delegate { OpenToolsCategory(); });

        survivalBTN = craftingScreenUI.transform.Find("SurvivalButton").GetComponent<Button>();
        survivalBTN.onClick.AddListener(delegate { OpenSurvivalCategory(); });

        refineBTN = craftingScreenUI.transform.Find("RefineButton").GetComponent<Button>();
        refineBTN.onClick.AddListener(delegate { OpenRefineCategory(); });

        constructionBTN = craftingScreenUI.transform.Find("ConstructionButton").GetComponent<Button>();
        constructionBTN.onClick.AddListener(delegate { OpenConstructionCategory(); });
        //Axe
        AxeReq2 = toolsScreenUI.transform.Find("Axe").transform.Find("req2").GetComponent<Text>();
        AxeReq1 = toolsScreenUI.transform.Find("Axe").transform.Find("req1").GetComponent<Text>();

        craftAxeBTN = toolsScreenUI.transform.Find("Axe").transform.Find("Button").GetComponent<Button>();
        craftAxeBTN.onClick.AddListener(delegate { CraftAnyItem(AxeBLP); });
        //Plank
        PlankReq1 = toolsScreenUI.transform.Find("Axe").transform.Find("req1").GetComponent<Text>();

        craftPlankBTN = RefineScreenUI.transform.Find("Plank").transform.Find("Button").GetComponent<Button>();
        craftPlankBTN.onClick.AddListener(delegate { CraftAnyItem(PlankBLP); });

        //Foundation

        FoundationReq1 = ConstructionScreenUI.transform.Find("Foundation").transform.Find("req1").GetComponent<Text>();

        craftFoundationBTN = ConstructionScreenUI.transform.Find("Foundation").transform.Find("Button").GetComponent<Button>();
        craftFoundationBTN.onClick.AddListener(delegate { CraftAnyItem(FoundationBLP); });

        //Wall
        WallReq1 = ConstructionScreenUI.transform.Find("Wall").transform.Find("req1").GetComponent<Text>();

        craftWallBTN = ConstructionScreenUI.transform.Find("Wall").transform.Find("Button").GetComponent<Button>();
        craftWallBTN.onClick.AddListener(delegate { CraftAnyItem(WallBLP); });

    }

    void OpenToolsCategory()
    {
        craftingScreenUI.SetActive(false);
        RefineScreenUI.SetActive(false);
        SurvivalScreenUI.SetActive(false);
        ConstructionScreenUI.SetActive(false);
        toolsScreenUI.SetActive(true);
    }

    void OpenSurvivalCategory()
    {
        craftingScreenUI.SetActive(false);
        toolsScreenUI.SetActive(false);
        RefineScreenUI.SetActive(false);
        ConstructionScreenUI.SetActive(false);
        SurvivalScreenUI.SetActive(true);

    }

    void OpenRefineCategory()
    {
        craftingScreenUI.SetActive(false);
        toolsScreenUI.SetActive(false);
        SurvivalScreenUI.SetActive(false);
        ConstructionScreenUI.SetActive(false);
        RefineScreenUI.SetActive(true);
       
    }

    void OpenConstructionCategory()
    {
        craftingScreenUI.SetActive(false);
        RefineScreenUI.SetActive(false);
        SurvivalScreenUI.SetActive(false);
        toolsScreenUI.SetActive(false);
        ConstructionScreenUI.SetActive(true);
    }

    void CraftAnyItem(Blueprint blueprintToCraft)

    {

        SoundManager.instance.PlaySound(SoundManager.instance.craftingSound);
        if (blueprintToCraft.numberOfItemsToProduce == 1)
        {
            InventorySystem.Instance.AddToInventory(blueprintToCraft.itemName);
        }
        else if (blueprintToCraft.numberOfItemsToProduce == 2)
        {
            InventorySystem.Instance.AddToInventory(blueprintToCraft.itemName);
            InventorySystem.Instance.AddToInventory(blueprintToCraft.itemName);
        }




        InventorySystem.Instance.AddToInventory(blueprintToCraft.itemName);

        if (blueprintToCraft.numOfRequirements == 1)
        {
            InventorySystem.Instance.RemoveItem(blueprintToCraft.Req1, blueprintToCraft.Req1amount);
        }

        else if (blueprintToCraft.numOfRequirements == 2)
        {
            InventorySystem.Instance.RemoveItem(blueprintToCraft.Req1, blueprintToCraft.Req1amount);
            InventorySystem.Instance.RemoveItem(blueprintToCraft.Req2, blueprintToCraft.Req2amount);

        }

        InventorySystem.Instance.ReCalculateList();

        StartCoroutine(calculate());

        RefreshNeededItems();
    }

    private void StartCoroutine(IEnumerable enumerable)
    {
        throw new NotImplementedException();
    }

    public IEnumerable calculate()
    {
        yield return new WaitForSeconds(1f);
        InventorySystem.Instance.ReCalculateList();
        RefreshNeededItems();
    }



    // Update is called once per frame
    void Update()
    {



       




        if (Input.GetKeyDown(KeyCode.C) && !isOpen)
        {

           
            craftingScreenUI.SetActive(true);
           
            Cursor.lockState = CursorLockMode.None;
            Cursor.visible = true;
            SelectionManager.instance.DisableSelection();
            SelectionManager.instance.GetComponent<SelectionManager>().enabled = false;
            isOpen = true;

        }
        else if (Input.GetKeyDown(KeyCode.C) && isOpen)
        {
            craftingScreenUI.SetActive(false);
            toolsScreenUI.SetActive(false);
            SurvivalScreenUI.SetActive(false);
            RefineScreenUI.SetActive(false);
            ConstructionScreenUI.SetActive(false);




            if (!InventorySystem.Instance.isOpen)
            {
                Cursor.lockState = CursorLockMode.Locked;
                Cursor.visible = false;

                SelectionManager.instance.EnableSelection();
                SelectionManager.instance.GetComponent<SelectionManager>().enabled = true;
            }

            isOpen = false;
        }
      
    }

    public void RefreshNeededItems()
    {
        int stone_count = 0;
        int stick_count = 0;
        int log_count = 0;
        int plank_count = 0;

        inventoryItemList = InventorySystem.Instance.itemList;

        foreach(string itemName in inventoryItemList)
        {
            switch(itemName)
            {
              
                case "Stone":
                    stone_count += 1;
                    break;
                case "Stick":
                    stick_count += 1;
                    break;

                case "Log":
                    log_count += 1;
                    break;

                case "Plank":
                    plank_count += 1;
                    break;

            }
        }   
        //Axe
            AxeReq1.text = "2 Stone [" + stone_count + "]";
            AxeReq2.text = "3 Stick [" + stick_count + "]";

        if(stone_count >=2  && stick_count >=3 && InventorySystem.Instance.CheckSlotsAvailable(1))
        {
            craftAxeBTN.gameObject.SetActive(true);
        }
        else
        {
            craftAxeBTN.gameObject.SetActive(false);
        }

        //Plank
        PlankReq1.text = "1 Log [" + log_count + "]";
      

        if (log_count >=1 && InventorySystem.Instance.CheckSlotsAvailable(2))
        {
            craftPlankBTN.gameObject.SetActive(true);
        }
        else
        {
            craftPlankBTN.gameObject.SetActive(false);
        }

        //Foundation

        FoundationReq1.text = "4 Plank [" + plank_count + "]";


        if (plank_count >= 1 && InventorySystem.Instance.CheckSlotsAvailable(4))
        {
            craftFoundationBTN.gameObject.SetActive(true);
        }
        else
        {
            craftFoundationBTN.gameObject.SetActive(false);
        }

        //Wall

        WallReq1.text = "5 Plank [" + plank_count + "]";


        if (plank_count >= 1 && InventorySystem.Instance.CheckSlotsAvailable(2))
        {
            craftFoundationBTN.gameObject.SetActive(true);
        }
        else
        {
            craftFoundationBTN.gameObject.SetActive(false);
        }



    }



}

What about the Blueprint class itself? You still haven’t showed us that.

I dont think the issue is in that code. I guess you have your Blueprint class in a seperate script and its inheriting by MonoBehaviour. I dont know what else that script is doing but if possible you want to delete that inheritance or create a nested class.