获取组件方法 GetComponent

目前正跟随官网 Junior Programmer 课程学习。

前一段时间学习到的一些内容,将分别纪要。

1.获取组件

获取组件 GetComponent() 方法有两个重载:

1.1 使用组件类

性能更好;

1
GetComponent (Type type);

如果游戏对象附加了类型为 type 的组件,则将其返回,否则返回 null

1
2
3
4
5
6
7
8
9
using UnityEngine;public class ScriptExample : MonoBehaviour
{
void Start()
{
// 在当前游戏对象的铰链组件中,关闭弹簧效果
HingeJoint hinge = GetComponent<HingeJoint>();
hinge.useSpring = false;
}
}

以上。

1.2 使用组件名

性能略低;

1
public Component GetComponent (string type);

如果游戏对象附加了名为 type 的组件,则将其返回,否则返回 null。

出于性能原因,最好使用具有 Type 而不是字符串的 GetComponent。 但有时可能无法访问该类型,例如在尝试从 Javascript 访问 C# 脚本时。 在这种情况下,可以仅根据名称而不是类型访问该组件。

示例:

1
2
3
4
5
6
7
8
9
using UnityEngine;public class ScriptExample : MonoBehaviour
{
void Start()
{
// 在当前游戏对象的铰链组件中,关闭弹簧效果
HingeJoint hinge = GetComponent("HingeJoint") as HingeJoint;
hinge.useSpring = false;
}
}

以上。