Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Majnun · Dec 21, 2013 at 04:21 AM · c#gameobjectinstantiatecomponent

AddComponent() causes a "trying to create a MonoBehaviour using the 'new' keyword" warning

I'm attempting to create a "game instance" singleton. Things have been working fine for a while, and still are, but I notice a warning that I either didn't notice was there before or is new. (I suspect I just didn't notice it before). Again things seem like they are working, but I don't like this warning sitting around in the console taunting me. What am I doing wrong?


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()
TableObject:.ctor()
Game:.ctor()
UnityEngine.GameObject:AddComponent()
Game:get_Instance() (at Assets/Scripts/Game.cs:28)
Commodity:Awake() (at Assets/Scripts/Commodity.cs:15)


Note: Commodity:Awake() is doing this: Game.Instance.AddCommodity(this); //adds the commodity to a List property on Game

Game.Instance:

 public class Game : MonoBehaviour {
     
     
     // GAME INSTANCE *********************************************
     private static Game instance;
     public static Game Instance
     {
         get
         {
             // Unity destroys objects in random order (or so says the internet).
             // This makes sure we don't accidentally create it again if something asks for it after it's been destroyed (which leaves a ghost object in the scene after hitting the stop play button)
             if (applicationIsQuitting) {
                 Debug.LogWarning("Game Instance already destroyed on application quit. Won't create again - returning null.");
                 return null;
             }
  
             // If the instance doesn't exist yet, make it.
             if(instance == null)
             {
                 Debug.Log("Creating new Game Instance.");
 
                 //this generates a warning:
                 instance = new GameObject("Game").AddComponent<Game>();
 
                 GameObject.DontDestroyOnLoad(instance);
             }
             
             
             // return the instance
             return instance;
             
             
         }
     }
             
     // Sets the instance to null when the application quits
     private static bool applicationIsQuitting = false;
     public void OnApplicationQuit()
     { 
         applicationIsQuitting = true;
         instance = null; 
     
     }
     //*************************************************************
 
 //... other stuff

I also tried changing this "`instance = new GameObject("Game").AddComponent();`" to:

                 GameObject newGO = new GameObject();
                 newGO.name = "Game";
                 newGO.AddComponent<Game>();
                 instance = newGO.GetComponent<Game>();

But I get the same error at newGo.AddComponent(); Which suggests AddComponent is doing something that is triggering that warning. Or something in Game class is causing the problem... let me know folks want me to post the whole class (it's kind of long). I'm hoping just the singleton implementation part is all that is needed to help spot the problem.

I'm at a loss. Especially since things appear to be working just fine. I get a new object called "Game" in the scene, and it has a Game component on it with all the variables I'm setting on it externally via and properties like Game.Instance.XXX

Any help is greatly appreciated.

Thanks! :)

Comment
Add comment · Show 3
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Majnun · Dec 21, 2013 at 01:53 AM 0
Share

Hmmm, looking closer at the warning, I don't understand why TableObject (another class in my project) is involved at all... maybe that's somehow related. (I'm assu$$anonymous$$g ctor() is constructor?)

avatar image Majnun · Dec 21, 2013 at 04:32 AM 0
Share

Yep that was culprit. Elsewhere in the Game script I was incorrectly creating a Property with "new" TableObject which is a $$anonymous$$onoBehavior. That was confusing because doubleclicking on the error took me the line where I was calling AddComponent().

avatar image Benproductions1 · Dec 21, 2013 at 04:34 AM 0
Share

The problem doesn't seem to be related to the code you posted. Perhaps there's a problem somewhere else. It might be a good idea to remove scripts/code until you've narrowed down the problem space

2 Replies

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by Majnun · Dec 21, 2013 at 04:37 AM

Figured it out. I had a property to a MonoBehavior elsewhere in the Game class. (A TableObject) which I declared incorrecly using new.

Like so: TableObject StartingSupplies = new TableObject()

So the warning was actually about this line, but it was saying it was about the AddComponent(); line.

Hopefully this self-answered question will help others if they are in a similar situation and confused by a similar issue. (Double clicking the warning took me to the line with the AddComponent rather than the actual problem which was incorrectly creating the TableObject with "new".

Thanks all. :)

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
-1

Answer by thaiscorpion · Dec 21, 2013 at 04:36 AM

Please ignore this answer, thanks!

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Majnun · Dec 21, 2013 at 05:25 AM 1
Share

Nothing was wrong with the instance = new GameObject("Game").AddComponent(); Double clicking the warning just took me there for some reason. The real problem was declaring a Property (with a New constructor) to a $$anonymous$$onoBehavior elsewhere in that script. Once I fixed that by removing the = new my$$anonymous$$onoBehaviorExtendedClass() it worked fine.

avatar image thaiscorpion · Dec 21, 2013 at 03:55 PM 0
Share

@$$anonymous$$ajnun Oh oky I just had this code like that in my project and it worked perfectly, and since you said yours didn't I thought it might have been that, but nvm :D

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

20 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

C# Adding Components From Other Gameobjects 3 Answers

Classes and Scripting 2 Answers

GameManager class doesn't accept GameObject.Find() 0 Answers

Null Reference Exception on instantiated object's script. 2 Answers

Weird Glitch When Instantiating a Game Object 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges