• 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 MeafQ · May 20, 2019 at 06:28 AM · gameobjecteditor

new GameObject returns null

 [ExecuteInEditMode]
 public class Test : MonoBehaviour
 {
     private GameObject _gameObject;
     
     void Reset()
     {
         _gameObject = new GameObject();
         Debug.Log(_gameObject);
     }
 }
 

I have no idea why it returns null only when I add a component to a gameobject, but for example, if I click Reset on it later on it will return a GameObject.

Also EditorUtility.CreateGameObjectWithHideFlags works fine.

UPDATE: I want to do so to create a folder-like GameObject to store all components that script needs. Also seems like it is an inconsistent behaviour, no idea what causes it (Unity version, project settings?).

Comment
Add comment · Show 11
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 jojizaidi · May 20, 2019 at 07:16 AM 0
Share

Because in the reset function you're actually initializing the _gameObject.

private GameObject _gameObject just defines a game object. It does not allocate memory to it. You can write private GameObject _gameObject = new GameObject();

avatar image Bonfire-Boy jojizaidi · May 20, 2019 at 11:12 AM 0
Share

@jojizaidi They are already assigning the new GameObject to a variable in the function, in the way you suggest. It's not allowed to do it in the declaration of the variable (which, from the private you've added appears to be what you're suggesting)

avatar image jojizaidi Bonfire-Boy · May 21, 2019 at 04:52 AM 0
Share

$$anonymous$$y bad you cant do it in the declaration, but you can just define a private gameobject and in the start method do _gameObject = new GameObject() This will create an empty game object in the Hierarchy and then you can just add components or whatever you want to it.

avatar image Bonfire-Boy · May 20, 2019 at 11:11 AM 0
Share

In Play mode I would expect this to work fine.

But are you doing it in Edit mode? If so then try making your field public ins$$anonymous$$d of private, so that it gets serialised.

avatar image MeafQ Bonfire-Boy · May 21, 2019 at 07:23 AM 0
Share

@Bonfire-Boy I tried it and a whole lot of other things.

 using UnityEngine;
 
 [ExecuteInEdit$$anonymous$$ode]
 public class Test : $$anonymous$$onoBehaviour
 {
     private GameObject _gameObject1;
     public GameObject _gameObject2;
     [SerializeField] private GameObject _gameObject3;
     private bool _update = true;
     
     private void Reset()
     {
         _gameObject1 = new GameObject();
         _gameObject2 = new GameObject();
         _gameObject3 = new GameObject();
         Debug.Log("Reset: " + _gameObject1 + " " + _gameObject2 + " " + _gameObject3);
     }
 
     private void Awake()
     {
         _gameObject1 = new GameObject();
         _gameObject2 = new GameObject();
         _gameObject3 = new GameObject();
         Debug.Log("Awake: " + _gameObject1 + " " + _gameObject2 + " " + _gameObject3);
     }
 
     private void Start()
     {
         _gameObject1 = new GameObject();
         _gameObject2 = new GameObject();
         _gameObject3 = new GameObject();
         Debug.Log("Start: " + _gameObject1 + " " + _gameObject2 + " " + _gameObject3);
     }
     
     private void Update()
     {
         while (_update)
         {
             _gameObject1 = new GameObject();
             _gameObject2 = new GameObject();
             _gameObject3 = new GameObject();
             Debug.Log("Update: " + _gameObject1 + " " + _gameObject2 + " " + _gameObject3);
             _update = false;
         }
     }
 }
 

alt text

avatar image MeafQ Bonfire-Boy · May 21, 2019 at 07:24 AM 0
Share

So basically it works only after Awake, OnEnable, Reset (gameobject is always created but just without a return in those cases) https://docs.unity3d.com/$$anonymous$$anual/ExecutionOrder.html

avatar image jojizaidi MeafQ · May 21, 2019 at 07:26 AM 0
Share

What are you trying to achieve actually. And why do you want to use [ExecuteInEdit$$anonymous$$ode]

In Start method it is able to create a new GameObject. If you tell your scenario as in what you want to do we might be able to help you better

Show more comments
avatar image troien · May 24, 2019 at 03:04 PM 0
Share

I actually copy-pasted your code and tested it in an empty scene. And it seems to work as you want it to work (both when dragging/dropping Test script on a GameObject and when hitting reset), how are you adding this Test component in the first place?

avatar image MeafQ troien · May 24, 2019 at 04:11 PM 0
Share

$$anonymous$$ine performs completely opposite, I did all the things you said. $$anonymous$$ay be something about Unity, project settings?

avatar image troien · May 24, 2019 at 04:55 PM 0
Share

Although I agree with others that you shouldn't do this (mostly for reasons told by Bunny83's answer) this seems like you are experiencing some sort of bug. Because even the following code works as expected, when I add example2 to a gameobject, it will log both created gameobjects correctly. Tested in both Unity 2018.4.0f1 and Unity 2019.1.3f1...

 [ExecuteInEdit$$anonymous$$ode]
 public class Example : $$anonymous$$onoBehaviour
 {
     private GameObject _gameObject;
 
     void Reset()
     {
         _gameObject = new GameObject();
         Debug.Log(_gameObject, _gameObject);
     }
 }

and

 [ExecuteInEdit$$anonymous$$ode]
     public class Example2 : $$anonymous$$onoBehaviour
     {
         private GameObject _gameObject;
     
         void Reset()
         {
             _gameObject = new GameObject();
             _gameObject.AddComponent<Example>();
             Debug.Log(_gameObject, _gameObject);
         }
     }

5 Replies

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

Answer by Bunny83 · May 24, 2019 at 04:09 PM

You really don't want to put gameobject generating code inside the editor only Reset callback. Especially you create the gameobject unconditionally. Furthermore you store the reference in a non serialized private variable. So this reference will not be saved at all. Finally there could be issues when / from where Unity calls the Reset method. Also that "ExecuteInEditMode" attribute looks like some abusive usage. "ExecuteInEditMode" is not meant for providing editor features. It's just meant to have runtime features work during edit time (like particle effects, and stuff like that).


It's not clear what you actually want to achieve. If the object this script is attached to requires another gameobject (for some reason), why don't you make a prefab that includes that gameobject? If you really want to create the gameobject on the fly, just use some lazy loading whenever you actually need it.

 private GameObject m_Obj = null;
 public GameObject Obj
 {
     get {
         if (m_Obj == null)
             m_Obj = new GameObject("tmpObj");
         return m_Obj;
     }
 }

Now whenever you need to work with your extra gameobject, just use the "Obj" property and it will create the gameobject on the fly if it hasn't been created yet. Though be warned, as i said above, you should avoid things like that at edit time since the created gameobject will be part of the current scene and mark the scene dirty.


It would be much easier for us to help you if we know what you actually wanted to achieve. Editor functionality does not belong into MonoBehaviour scripts unless you really know what you're doing.

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 MeafQ · May 24, 2019 at 04:14 PM 0
Share

I want to have a folder-like GameObject for all components that script creates.

avatar image Bonfire-Boy MeafQ · May 25, 2019 at 06:02 PM 1
Share

Do you mean a folder-like GameObject for other GameObjects that the script creates? Note that "component" has a specific meaning in Unity, If you're creating components on your new GameObject then it's hardly the "empty, folder-like" GameObject you've talked about.

There is absolutely no reason you can't do what you're talking about, and if you keep it out of monobehaviour callback functions and write editor-specific code, with editor-specific idioms rather than play mode idioms, then it's not difficult.

But I think when you're asked what you're trying to achieve here the important thing is not the end result - it's how and when you're trying to achieve it. How are you triggering this process? From a menu item? The fact that you're showing us code in functions that shouldn't be involved, makes it very hard to work out.
Note that one problem with Bunny's form of lazy instantiation is that every time you use Obj it'll create a new container (because the private backing field isn't serialised). So you might want to use Find here something like this .

 const string CONTAINERNA$$anonymous$$E="Container";
 public GameObject Obj
 {
      get {
          GameObject g = GameObject.Find(CONTAINERNA$$anonymous$$E);
          if (g==null)
              g = new GameObject(CONTAINERNA$$anonymous$$E);
          return g;
      }
 }
 

This way you could for example have a menu item that creates things in your container, and once its created the container it will use that container on subsequent calls, rather than make a new one.

avatar image
1

Answer by Captain_Pineapple · May 20, 2019 at 10:13 AM

As already pointed out this does not "instantiate" any object. As a rule for most applications: Never use "new" when handling any Gameobject, transform or component! Use Instantiate when you want to create an object in your scene

If you want to add components to an gameobject by script this is done by using gameObject.AddComponent


As i said, as a general rule never use new for any monobehaviourrelated stuff.

Comment
Add comment · Show 10 · 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 Bonfire-Boy · May 20, 2019 at 11:10 AM 3
Share

This is just plain wrong.

You certainly shouldn't use new to create a $$anonymous$$onoBehaviour. But they're not. They're creating a GameObject. And GameObject has constructors that are fine to use and do create GameObjects. I use it all the time.

avatar image PixxlMan Bonfire-Boy · May 24, 2019 at 02:08 PM 0
Share

Wait, really? So I could just write

 new $$anonymous$$yPrefab(something)

and it would instantiate?

avatar image Bunny83 PixxlMan · May 24, 2019 at 03:57 PM 0
Share

We talked about the GameObject class, nothing else. Components must not / can not be created with new since you have to use AddComponent on a gameobject. Components can't live on their own.


I'm not sure what "$$anonymous$$yPrefab" represents in your case. Prefabs are generally premade serialized objects and not classes. So "new" is completely off topic in this field. The GameObject class has several constructor overloads to create new gameobjects while the Component class as well as the $$anonymous$$onoBehaviour class doesn't have one. (well they have a parameterless constructor, but it's not meant to be called by you)

avatar image MeafQ · May 21, 2019 at 07:17 AM 0
Share

I'm doing like that based on documentation as I just want a simple empty gameobject.

avatar image jojizaidi MeafQ · May 21, 2019 at 07:20 AM 0
Share
 [ExecuteInEdit$$anonymous$$ode]
 public class Test : $$anonymous$$onoBehaviour
 {
     private GameObject _gameObject;
 
     private void Start()
     {
         if (_gameObject == null)
         {
             _gameObject = new GameObject();
             _gameObject.name = "$$anonymous$$yGameObject";
         }
     }
     void Reset()
     {
         _gameObject = new GameObject();
         Debug.Log(_gameObject);
     }
 }

This will work

avatar image MeafQ jojizaidi · May 21, 2019 at 07:31 AM 0
Share

It would somewhat work if "new GameObject()" would just return null but it returns null and creates a GameObject. So this what happened to me. alt text

Show more comments
avatar image SunnyPalmSprings · May 21, 2019 at 03:01 PM 0
Share

What about for a $$anonymous$$esh Filter? I find if I ever want to edit the mesh, I first have to use meshFilter = new $$anonymous$$esh();

avatar image Bonfire-Boy SunnyPalmSprings · May 21, 2019 at 04:28 PM 0
Share

@SunnyPalmSprings With respect, that has nothing to do with this question. If you have a problem with meshes and mesh filters then you should post a new question with details.

avatar image
-3

Answer by Raykneet · May 21, 2019 at 06:35 AM

Creating a gameObject will create a variable which is able to store a gameObject from the scene. When using 'new' you not actually instantiating a new object, you are basically doing nothing. Use instantiate() to create a new gameobject. You can use a oprefab for spawning a specific gameobject.

Comment
Add comment · Show 1 · 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 jojizaidi · May 21, 2019 at 06:38 AM 1
Share

I'm afraid you're wrong.

When you write _gameObject = new GameObject() , a new GameObject is created in the Hierarchy i.e. an empty GameObject is instantiated.

avatar image
0

Answer by Pablomon · Apr 03, 2020 at 11:34 AM

I came across the same "feature": new GameObject() returns null when Reset gets called by adding a component in the inspector but works perfectly fine when clicking the reset button.

I found a workaround:

 private void Reset()
 {
      // calling new Gameobject on reset returns null. 
      // This is the hack I found to work best
      StartCoroutine(CreateEmptyGameObject());
 }
 
 IEnumerator CreateEmptyGameObject()
 {
      yield return null;
      GameObject go;
      go = new GameObject("Empty game object");
      // now go has a reference to the game object as expected     
      // and you can code your stuff
      ...
 }

I guess Unity doesn't update the hierarchy cache quick enough? Anyway, this works just fine.

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
0

Answer by canis · Oct 13, 2020 at 03:10 AM

Here is my solution.

 void Reset()
 {
     Invoke(nameof(Editor_Init), 0); // try not to use "string" type here,
     // instead we can use nameof() to label which function call we using.
     // process in next ZERO second is a hack, to run the same thing without error.
 }
 
 void Editor_Init()
 {
     GameObject go = new GameObject("Sub-Folder");
     go.transform.SetParent(transform); // will work like this. ya~~~
 }

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

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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

191 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 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 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 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 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 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 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 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 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 avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Finding multiple objects by the same tag as to place them in one array? 2 Answers

Is there anyway to batch renaming via Editor [not on Runtime] multiple game objects in the hierarchy ? 4 Answers

OnDestroy() callback in Editor upon deleting selected GameObject - del key 5 Answers

GameObject won't appear in Game view 2 Answers

keep gameObject in hierarchy folded when not selected 3 Answers


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