1

Say I had a prefab called Bullet with a script attached called BulletControl.cs.

I could instantiate it as: GameObject bulletInstance = Instantiate(Bullet, transform); Or I could do: BulletControl bulletInstance = Instantiate(Bullet, transform);

I originally thought that instantiating as a GameObject was just a more general type that gave you access to other parameters like transform. Instantiating, to my understanding, isn't like using the new keyword, so I don't think that when I declare bulletInstance's type I'm creating an instance of the class BulletControl. What's going on here?

Null Salad
  • 765
  • 2
  • 16
  • 31

1 Answers1

1

The Instantiate function takes Object as argument.

In Unity, every GameObject and components/scripts inherits from Object directly or indirectly.

Let's say that the name of your script is called YourScript:

YourScript inherits from MonoBehaviour

public class YourScript : MonoBehaviour
{

}

then MonoBehaviour inherits from Behaviour

public class MonoBehaviour : Behaviour
{

}

and Behaviour inherits from Component.

public class Behaviour : Component
{

}

Finally, Component inherits from Object.

public class Component : Object
{

}

For GameObject, it inherits from Object directly.

public sealed class GameObject : Object
{

}

Because of this, any class that inherits from Object should be able to be instantiated with the Instantiate function.

Instantiating, to my understanding, isn't like using the new keyword

If your script does not inherit from MonoBehaviour then you can use the new keyword to create a new instance of it like a normal C# program. If it inherits from MonoBehaviour, you have to use the Instantiate or the AddComponent function. See this post for more information.

Programmer
  • 121,791
  • 22
  • 236
  • 328
  • Also, Instantiate is faster than creation by code when it comes to add many components. At least, one quick benchmark we did showed so. Could be that since Unity knows ahead what the prefab requires, it may optimize the process. To be confirmed. – Everts May 31 '17 at 06:49
  • *"Instantiate is faster than creation by code"* Can you explain what you mean by creation by code? – Programmer May 31 '17 at 07:06
  • When you have GameObject obj = new GameObject("name", typeof(SomeType), typeof(SomeOtherType)); and then you have a prefab with already attached types and you use Instantiate(prefab), we noticed it goes faster by a large scale. It was in our case, but I can't rule it for all cases so this is why I say to be confirmed. – Everts May 31 '17 at 07:09
  • Oh I see. I haven't really done that test but that might be true. It seems like the first method you mentioned is using reflection a-lot. Plus, it takes string as a parameter for the name of the GameObject..That string could cause memory allocation just like `GameObject.tag`. Maybe those are the reasons. – Programmer May 31 '17 at 07:25