Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

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

Discussion in 'Getting Started' started by unity_C3026BB9FC74A74B0EE2, Aug 8, 2023.

?

Ive created this script& it shows this message"MonoBehaviour using the ‘new’ keyword. "how do i fix?

  1. You have to change..... and .....

    0 vote(s)
    0.0%
  2. whrite.....and change....

    0 vote(s)
    0.0%
Multiple votes are allowed.
  1. unity_C3026BB9FC74A74B0EE2

    unity_C3026BB9FC74A74B0EE2

    Joined:
    Jun 16, 2023
    Posts:
    4
    I have made this Script:

    Start of the Script:

    Code (CSharp):
    1. using System;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using Unity.VisualScripting;
    5. using UnityEngine;
    6. using UnityEngine.UI;
    7. public class CraftingSystem : MonoBehaviour
    8. {
    9.     public GameObject craftingScreenUI;
    10.     public GameObject toolsScreenUI, SurvivalScreenUI, RefineScreenUI, ConstructionScreenUI;
    11.  
    12.     public List<string> inventoryItemList = new List<string>();
    13.     Button toolsBTN, survivalBTN, refineBTN, constructionBTN;
    14.     Button craftAxeBTN, craftPlankBTN, craftFoundationBTN, craftWallBTN;
    15.     Text AxeReq1, AxeReq2, PlankReq1, FoundationReq1, WallReq1;
    16.     public bool isOpen;
    17.  
    18.     public Blueprint AxeBLP = new Blueprint("Axe", 1, 2, "Stone", 2, "Stick", 3); // new muss ersetz werden.
    19.     public Blueprint PlankBLP = new Blueprint("Plank", 2, 1, "Log", 1, "", 0); // new muss ersetz werden.
    20.     public Blueprint FoundationBLP = new Blueprint("Foundation", 1, 1, "Plank", 4, "", 0);// new muss ersetz werden.
    21.     public Blueprint WallBLP = new Blueprint("Wall", 1, 1, "Plank", 5, "", 0);// new muss ersetz werden.
    22.     public static CraftingSystem Instance { get; set; }
    23.     public void Awake()
    24.     {
    25.         if (Instance != null && Instance != this)
    26.         {
    27.             Destroy(gameObject);
    28.         }
    29.         else
    30.         {
    31.             Instance = this;
    32.         }
    33.     }


    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().
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563
    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<T>() 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.
     
    bugfinders likes this.
  3. unity_C3026BB9FC74A74B0EE2

    unity_C3026BB9FC74A74B0EE2

    Joined:
    Jun 16, 2023
    Posts:
    4
    thank you verry much. Can you pleas show me in my code what I have to do?
     
  4. AngryProgrammer

    AngryProgrammer

    Joined:
    Jun 4, 2019
    Posts:
    431
    Last edited: Aug 9, 2023
  5. unity_C3026BB9FC74A74B0EE2

    unity_C3026BB9FC74A74B0EE2

    Joined:
    Jun 16, 2023
    Posts:
    4
    Can you please show me in my Code, where I have to do it.
     
  6. AngryProgrammer

    AngryProgrammer

    Joined:
    Jun 4, 2019
    Posts:
    431
    You must post what Blueprint is because if the class Blueprint inherits from MonoBehaviour you can't use a new keyword.
     
  7. unity_C3026BB9FC74A74B0EE2

    unity_C3026BB9FC74A74B0EE2

    Joined:
    Jun 16, 2023
    Posts:
    4
    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


    Code (CSharp):
    1. using System;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using Unity.VisualScripting;
    5. using UnityEngine;
    6. using UnityEngine.UI;
    7.  
    8.  
    9. public class CraftingSystem : MonoBehaviour
    10. {
    11.     public GameObject craftingScreenUI;
    12.     public GameObject toolsScreenUI, SurvivalScreenUI, RefineScreenUI, ConstructionScreenUI;
    13.    
    14.  
    15.  
    16.     public List<string> inventoryItemList = new List<string>();
    17.  
    18.     Button toolsBTN, survivalBTN, refineBTN, constructionBTN;
    19.  
    20.     Button craftAxeBTN, craftPlankBTN, craftFoundationBTN, craftWallBTN;
    21.  
    22.     Text AxeReq1, AxeReq2, PlankReq1, FoundationReq1, WallReq1;
    23.  
    24.     public bool isOpen;
    25.  
    26.  
    27.  
    28.     public Blueprint AxeBLP = new Blueprint("Axe", 1, 2, "Stone", 2, "Stick", 3);
    29.     public Blueprint PlankBLP = new Blueprint("Plank", 2, 1, "Log", 1, "", 0);
    30.     public Blueprint FoundationBLP = new Blueprint("Foundation", 1, 1, "Plank", 4, "", 0);
    31.     public Blueprint WallBLP = new Blueprint("Wall", 1, 1, "Plank", 5, "", 0);
    32.  
    33.     public static CraftingSystem Instance { get; set; }
    34.  
    35.     public void Awake()
    36.     {
    37.         if (Instance != null && Instance != this)
    38.         {
    39.             Destroy(gameObject);
    40.  
    41.         }
    42.         else
    43.         {
    44.             Instance = this;
    45.         }
    46.     }
    47.  
    48.     // Start is called before the first frame update
    49.     void Start()
    50.     {
    51.         isOpen = false;
    52.  
    53.         toolsBTN = craftingScreenUI.transform.Find("ToolsButton").GetComponent<Button>();
    54.         toolsBTN.onClick.AddListener(delegate { OpenToolsCategory(); });
    55.  
    56.         survivalBTN = craftingScreenUI.transform.Find("SurvivalButton").GetComponent<Button>();
    57.         survivalBTN.onClick.AddListener(delegate { OpenSurvivalCategory(); });
    58.  
    59.         refineBTN = craftingScreenUI.transform.Find("RefineButton").GetComponent<Button>();
    60.         refineBTN.onClick.AddListener(delegate { OpenRefineCategory(); });
    61.  
    62.         constructionBTN = craftingScreenUI.transform.Find("ConstructionButton").GetComponent<Button>();
    63.         constructionBTN.onClick.AddListener(delegate { OpenConstructionCategory(); });
    64.         //Axe
    65.         AxeReq2 = toolsScreenUI.transform.Find("Axe").transform.Find("req2").GetComponent<Text>();
    66.         AxeReq1 = toolsScreenUI.transform.Find("Axe").transform.Find("req1").GetComponent<Text>();
    67.  
    68.         craftAxeBTN = toolsScreenUI.transform.Find("Axe").transform.Find("Button").GetComponent<Button>();
    69.         craftAxeBTN.onClick.AddListener(delegate { CraftAnyItem(AxeBLP); });
    70.         //Plank
    71.         PlankReq1 = toolsScreenUI.transform.Find("Axe").transform.Find("req1").GetComponent<Text>();
    72.  
    73.         craftPlankBTN = RefineScreenUI.transform.Find("Plank").transform.Find("Button").GetComponent<Button>();
    74.         craftPlankBTN.onClick.AddListener(delegate { CraftAnyItem(PlankBLP); });
    75.  
    76.         //Foundation
    77.  
    78.         FoundationReq1 = ConstructionScreenUI.transform.Find("Foundation").transform.Find("req1").GetComponent<Text>();
    79.  
    80.         craftFoundationBTN = ConstructionScreenUI.transform.Find("Foundation").transform.Find("Button").GetComponent<Button>();
    81.         craftFoundationBTN.onClick.AddListener(delegate { CraftAnyItem(FoundationBLP); });
    82.  
    83.         //Wall
    84.         WallReq1 = ConstructionScreenUI.transform.Find("Wall").transform.Find("req1").GetComponent<Text>();
    85.  
    86.         craftWallBTN = ConstructionScreenUI.transform.Find("Wall").transform.Find("Button").GetComponent<Button>();
    87.         craftWallBTN.onClick.AddListener(delegate { CraftAnyItem(WallBLP); });
    88.  
    89.     }
    90.  
    91.     void OpenToolsCategory()
    92.     {
    93.         craftingScreenUI.SetActive(false);
    94.         RefineScreenUI.SetActive(false);
    95.         SurvivalScreenUI.SetActive(false);
    96.         ConstructionScreenUI.SetActive(false);
    97.         toolsScreenUI.SetActive(true);
    98.     }
    99.  
    100.     void OpenSurvivalCategory()
    101.     {
    102.         craftingScreenUI.SetActive(false);
    103.         toolsScreenUI.SetActive(false);
    104.         RefineScreenUI.SetActive(false);
    105.         ConstructionScreenUI.SetActive(false);
    106.         SurvivalScreenUI.SetActive(true);
    107.  
    108.     }
    109.  
    110.     void OpenRefineCategory()
    111.     {
    112.         craftingScreenUI.SetActive(false);
    113.         toolsScreenUI.SetActive(false);
    114.         SurvivalScreenUI.SetActive(false);
    115.         ConstructionScreenUI.SetActive(false);
    116.         RefineScreenUI.SetActive(true);
    117.        
    118.     }
    119.  
    120.     void OpenConstructionCategory()
    121.     {
    122.         craftingScreenUI.SetActive(false);
    123.         RefineScreenUI.SetActive(false);
    124.         SurvivalScreenUI.SetActive(false);
    125.         toolsScreenUI.SetActive(false);
    126.         ConstructionScreenUI.SetActive(true);
    127.     }
    128.  
    129.     void CraftAnyItem(Blueprint blueprintToCraft)
    130.  
    131.     {
    132.  
    133.         SoundManager.instance.PlaySound(SoundManager.instance.craftingSound);
    134.         if (blueprintToCraft.numberOfItemsToProduce == 1)
    135.         {
    136.             InventorySystem.Instance.AddToInventory(blueprintToCraft.itemName);
    137.         }
    138.         else if (blueprintToCraft.numberOfItemsToProduce == 2)
    139.         {
    140.             InventorySystem.Instance.AddToInventory(blueprintToCraft.itemName);
    141.             InventorySystem.Instance.AddToInventory(blueprintToCraft.itemName);
    142.         }
    143.  
    144.  
    145.  
    146.  
    147.         InventorySystem.Instance.AddToInventory(blueprintToCraft.itemName);
    148.  
    149.         if (blueprintToCraft.numOfRequirements == 1)
    150.         {
    151.             InventorySystem.Instance.RemoveItem(blueprintToCraft.Req1, blueprintToCraft.Req1amount);
    152.         }
    153.  
    154.         else if (blueprintToCraft.numOfRequirements == 2)
    155.         {
    156.             InventorySystem.Instance.RemoveItem(blueprintToCraft.Req1, blueprintToCraft.Req1amount);
    157.             InventorySystem.Instance.RemoveItem(blueprintToCraft.Req2, blueprintToCraft.Req2amount);
    158.  
    159.         }
    160.  
    161.         InventorySystem.Instance.ReCalculateList();
    162.  
    163.         StartCoroutine(calculate());
    164.  
    165.         RefreshNeededItems();
    166.     }
    167.  
    168.     private void StartCoroutine(IEnumerable enumerable)
    169.     {
    170.         throw new NotImplementedException();
    171.     }
    172.  
    173.     public IEnumerable calculate()
    174.     {
    175.         yield return new WaitForSeconds(1f);
    176.         InventorySystem.Instance.ReCalculateList();
    177.         RefreshNeededItems();
    178.     }
    179.  
    180.  
    181.  
    182.     // Update is called once per frame
    183.     void Update()
    184.     {
    185.  
    186.  
    187.  
    188.        
    189.  
    190.  
    191.  
    192.  
    193.         if (Input.GetKeyDown(KeyCode.C) && !isOpen)
    194.         {
    195.  
    196.            
    197.             craftingScreenUI.SetActive(true);
    198.            
    199.             Cursor.lockState = CursorLockMode.None;
    200.             Cursor.visible = true;
    201.             SelectionManager.instance.DisableSelection();
    202.             SelectionManager.instance.GetComponent<SelectionManager>().enabled = false;
    203.             isOpen = true;
    204.  
    205.         }
    206.         else if (Input.GetKeyDown(KeyCode.C) && isOpen)
    207.         {
    208.             craftingScreenUI.SetActive(false);
    209.             toolsScreenUI.SetActive(false);
    210.             SurvivalScreenUI.SetActive(false);
    211.             RefineScreenUI.SetActive(false);
    212.             ConstructionScreenUI.SetActive(false);
    213.  
    214.  
    215.  
    216.  
    217.             if (!InventorySystem.Instance.isOpen)
    218.             {
    219.                 Cursor.lockState = CursorLockMode.Locked;
    220.                 Cursor.visible = false;
    221.  
    222.                 SelectionManager.instance.EnableSelection();
    223.                 SelectionManager.instance.GetComponent<SelectionManager>().enabled = true;
    224.             }
    225.  
    226.             isOpen = false;
    227.         }
    228.      
    229.     }
    230.  
    231.     public void RefreshNeededItems()
    232.     {
    233.         int stone_count = 0;
    234.         int stick_count = 0;
    235.         int log_count = 0;
    236.         int plank_count = 0;
    237.  
    238.         inventoryItemList = InventorySystem.Instance.itemList;
    239.  
    240.         foreach(string itemName in inventoryItemList)
    241.         {
    242.             switch(itemName)
    243.             {
    244.              
    245.                 case "Stone":
    246.                     stone_count += 1;
    247.                     break;
    248.                 case "Stick":
    249.                     stick_count += 1;
    250.                     break;
    251.  
    252.                 case "Log":
    253.                     log_count += 1;
    254.                     break;
    255.  
    256.                 case "Plank":
    257.                     plank_count += 1;
    258.                     break;
    259.  
    260.             }
    261.         }  
    262.         //Axe
    263.             AxeReq1.text = "2 Stone [" + stone_count + "]";
    264.             AxeReq2.text = "3 Stick [" + stick_count + "]";
    265.  
    266.         if(stone_count >=2  && stick_count >=3 && InventorySystem.Instance.CheckSlotsAvailable(1))
    267.         {
    268.             craftAxeBTN.gameObject.SetActive(true);
    269.         }
    270.         else
    271.         {
    272.             craftAxeBTN.gameObject.SetActive(false);
    273.         }
    274.  
    275.         //Plank
    276.         PlankReq1.text = "1 Log [" + log_count + "]";
    277.      
    278.  
    279.         if (log_count >=1 && InventorySystem.Instance.CheckSlotsAvailable(2))
    280.         {
    281.             craftPlankBTN.gameObject.SetActive(true);
    282.         }
    283.         else
    284.         {
    285.             craftPlankBTN.gameObject.SetActive(false);
    286.         }
    287.  
    288.         //Foundation
    289.  
    290.         FoundationReq1.text = "4 Plank [" + plank_count + "]";
    291.  
    292.  
    293.         if (plank_count >= 1 && InventorySystem.Instance.CheckSlotsAvailable(4))
    294.         {
    295.             craftFoundationBTN.gameObject.SetActive(true);
    296.         }
    297.         else
    298.         {
    299.             craftFoundationBTN.gameObject.SetActive(false);
    300.         }
    301.  
    302.         //Wall
    303.  
    304.         WallReq1.text = "5 Plank [" + plank_count + "]";
    305.  
    306.  
    307.         if (plank_count >= 1 && InventorySystem.Instance.CheckSlotsAvailable(2))
    308.         {
    309.             craftFoundationBTN.gameObject.SetActive(true);
    310.         }
    311.         else
    312.         {
    313.             craftFoundationBTN.gameObject.SetActive(false);
    314.         }
    315.  
    316.  
    317.  
    318.     }
    319.  
    320.  
    321.  
    322. }
     
  8. Chubzdoomer

    Chubzdoomer

    Joined:
    Sep 27, 2014
    Posts:
    105
    What about the Blueprint class itself? You still haven't showed us that.