I'm using Unity4. Do I have to use new keyword for single game object? look at the following code.

1. GameObject obj = new GameObject(); obj = Resources.Load("Prefabs/Ball", typeof(GameObject)) as GameObject;

2. GameObject obj; obj = Resources.Load("Prefabs/Ball", typeof(GameObject)) as GameObject;

is it the same?


These are not the same. Resources.Load is going to create a new uninstantiated GameObject.

This means your first example is going to create a new game object, then set that object equal to the new game object created by Resources.Load. That means two objects are going to be created, an empty game object added to the scene (from the new GameObject() call) and an uninstantiated game object from the Resources.Load call.

It's worth noting that just using Resources.Load for a prefab will not create that prefab in the scene like new GameObject() creates a gameobject in the scene. Likely, what you intend to do is:

GameObject obj;
obj = GameObject.Instantiate(
         Resources.Load("Prefabs/Ball", typeof(GameObject))) as GameObject;

Note the additional use of Instantiate to create the loaded prefab into the scene.


In Addition to Byte56's answer, I'd like to mention that Unity forbids using new keyword for any MonoBehavior, since they are present in the scene and are already created. You'll most probably get a warning if you do that. You can create new Gameobject if you just want to have an empty GameObject in the scene.
You can't manually create a MonoBehavior using new keyword. You can however use Instantiate() for prefabs and AddComponent for Components. To use one of the already created MonoBehavior or GameObject which is present in the scene, you're encouraged to either make a public variable and drag the GameObject in the script from editor or use GameObject.Find() to use it directly from script without dragging and dropping. First method is faster and thus recommended way.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.