Unity3D/C#-将预制实例化为GameObject与组件类有什么区别? [英] Unity3D /C# - What's the difference between instantiating a prefab as a GameObject vs a component class?

查看:386
本文介绍了Unity3D/C#-将预制实例化为GameObject与组件类有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个名为Bullet的预制件,并带有一个名为BulletControl.cs的脚本.

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

我可以将其实例化为:GameObject bulletInstance = Instantiate(Bullet, transform); 或者我可以这样做:BulletControl bulletInstance = Instantiate(Bullet, transform);

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

我最初认为实例化为GameObject只是一种更通用的类型,它使您可以访问其他参数,例如transform.据我所知,实例化不像使用new关键字,因此我不认为在声明bulletInstance的类型时,我不会创建BulletControl类的实例.这是怎么回事?

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?

推荐答案

函数以 Object 作为参数.

The Instantiate function takes Object as argument.

在Unity中,每个GameObject和组件/脚本都继承自 Object 直接或间接.

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

假设您的脚本名称为YourScript:

YourScript继承自MonoBehaviour

public class YourScript : MonoBehaviour
{

}

然后MonoBehaviour继承自Behaviour

public class MonoBehaviour : Behaviour
{

}

Behaviour继承自Component.

public class Behaviour : Component
{

}

最后,Component继承自Object.

public class Component : Object
{

}


对于GameObject,它直接从Object继承.


For GameObject, it inherits from Object directly.

public sealed class GameObject : Object
{

}

因此,任何从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

如果脚本不是从MonoBehaviour继承的,则可以使用new关键字像普通的C#程序一样创建它的新实例.如果它继承自MonoBehaviour,则必须使用 Instantiate AddComponent 函数.有关更多信息,请参见帖子.

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.

这篇关于Unity3D/C#-将预制实例化为GameObject与组件类有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆