GameObject.AddComponent 添加组件

function AddComponent (className : string) : Component

Description描述

Adds a component class named className to the game object.

添加一个名称为className的组件到游戏物体。

Use this function to change behaviour of objects on the fly. You can also add script to game objects by passing in the name of the script class.
用这个函数改变运行中的物体的行为。你可以用传递脚本名称的方法,把程序脚本加载给游戏内物体。

Some components require other components to exist in the same game object as well. This function automatically adds any required components as well eg. if you add a HingeJoint this will automatically add a Rigidbody as well.
有些组件也需要同一个游戏物体有其他组件。当然这个函数会自动添加那些需要的组件,比如你添加一个HingeJoint组件,这个函数会自动添加一个Rigidbody组件。

using UnityEngine;

using System.Collections;



public class example : MonoBehaviour {

public SphereCollider sc;

public void Awake() {

gameObject.AddComponent("FoobarScript");

sc = gameObject.AddComponent("SphereCollider") as SphereCollider;

}

}
// Adds the script named FoobarScript to the game object

//给游戏物体添加名为FoobarScript的脚本

gameObject.AddComponent ("FoobarScript");



// Adds the sphere collider to the game object

//给游戏物体添加球体碰撞器

var sc : SphereCollider;

sc = gameObject.AddComponent ("SphereCollider");

o function AddComponent (componentType : Type) : Component

Description描述

Adds a component class of type componentType to the game object. C# Users can use a generic version

给游戏物体添加一个名称为componentType的组件类。C#用户可以用一个通用版本。

using UnityEngine;

using System.Collections;



public class example : MonoBehaviour {

	public FoobarScript fbs;

	public void Awake() {

		fbs = gameObject.AddComponent();

	}

}
var fbs : FoobarScript;

fbs = gameObject.AddComponent(FoobarScript);

Note that there is no RemoveComponent(), to remove a component, use Object.Destroy.

注意没有RemoveComponent()方法。如果你想去掉一个组件,可以使用Object.Destroy。

Page last updated: 2011-3-31