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

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

Discussion in 'Scripting' started by pKallv, Oct 17, 2014.

  1. pKallv

    pKallv

    Joined:
    Mar 2, 2014
    Posts:
    1,122
    I get the above error on the line marked below. I have found solutions, and tested, but do not get it to work for some reason. I guess it could be due to that this is a Singleton.

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4. using System;
    5.  
    6. public class Singleton : MonoBehaviour {
    7.  
    8.     //the singleton instance variable
    9.    private static Singleton _instance;
    10.  
    11.    //the property that lazy initializes the singleton instance and also provides it
    12.    public static Singleton Instance
    13.    {
    14.       get
    15.       {
    16.           //obtaining the mutual- exclusion lock to make instance thread-safe
    17.           lock (typeof(Singleton))
    18.           {
    19.              if (_instance == null) {
    20.                 _instance = new Singleton(); <<< Error is here >>>
    21.              }
    22.           }
    23.  
    24.           return_instance;
    25.         }
    26.     }
    27.  
    28.    //private access modifier to encapsulate the default constructor
    29.    private Singleton() {   }
    30.  
    31.    //just a sample property
    32.    //public bool Startup { get; set; }
    33.  
    34.    //just another sample method
    35.    public void PrintSettings ()
    36.    {
    37.       print ("Porsche 911 4S");
    38.    }
    39. }
    40.  
     
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,398
    MonoBehaviours can only be created as components, using AddComponent, as the error tells you.

    --Eric
     
    Graham-Dunnett likes this.
  3. pKallv

    pKallv

    Joined:
    Mar 2, 2014
    Posts:
    1,122
    I do understand that but the problem was that i did not got it to work. However, I now got it to work with this line:

    Code (csharp):
    1. _instance = GameObject.Find("ScriptObject").GetComponent<Singleton>();