Search Unity

You are trying to create a MonoBehaviour using the 'new' keyword.

Discussion in 'Scripting' started by Noamxrx, Jan 19, 2019.

  1. Noamxrx

    Noamxrx

    Joined:
    Jul 25, 2018
    Posts:
    42
    Hi!
    I trying to add "Tokens" from Another static script.
    Here is the scripts:

    The code that send the command:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class UseItem : MonoBehaviour
    5. {
    6.  
    7.     public static void Use(string ItemName)
    8.     {
    9.         Debug.Log("Custom item usage executing for item: " + ItemName);
    10.  
    11.         if (ItemName == "10 Tokens")
    12.         {
    13.             Tokens token = new Tokens();
    14.             token.Purchase10();
    15.         }
    16.     }
    17. }
    18.  
    The Script that should do the command:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using BayatGames.SaveGamePro;
    5.  
    6. public class Tokens : MonoBehaviour
    7. {
    8.     public int TOKENS = 0;
    9.     // Start is called before the first frame update
    10.     void Start()
    11.     {
    12.         TOKENS = SaveGame.Load<int>("TOKENS", TOKENS);
    13.     }
    14.  
    15.     // Update is called once per frame
    16.     void Update()
    17.     {
    18.         if (Input.GetButtonDown("Fire1"))
    19.         {
    20.             SaveGame.Save<int>("TOKENS", TOKENS);
    21.  
    22.         }
    23.     }
    24.     //buy
    25.     public void Purchase10()
    26.     {
    27.         TOKENS += 10;
    28.         Debug.Log("Success 10+");
    29.     }
    30. }
    The error i gets is:

    You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed. MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all
    UnityEngine.MonoBehaviour:.ctor()
    Tokens:.ctor() (at Assets/Scripts/Tokens.cs:8)
    UseItem:Use(String) (at Assets/Store/UseItem.cs:13)
    DialogScreenActions:onClickOk() (at Assets/Store/DialogScreenActions.cs:85)
    UnityEngine.EventSystems.EventSystem:Update()


    Thanks
    I hope you understand my problem.. It's a bit complicated to explain.
     
  2. Thibault-Potier

    Thibault-Potier

    Joined:
    Apr 10, 2015
    Posts:
    206
    Your Token Class inherit from monobehaviour.

    Thus you should'nt call "new" as the error message is telling you but AddComponent.

    Code (CSharp):
    1. Tokens token = new Tokens(); // do this with non monobehaviour c# class
    2.  
    3. Tokens token = gameObject.AddComponent<Tokens>(); // do this instead
     
    Noamxrx likes this.