问题描述
说我有一个名为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
继承的类都应该能够使用 Instantiate
函数.
Because of this, any class that inherits from Object
should be able to be instantiated with the Instantiate
function.
如果脚本不是从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与组件类有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!