组件包括脚本类、粒子类、物理类、声音类和渲染类等等。
添加游戏组件可以使用 AddComponent<组件名>() 的方法。组件自身没有对应的删除方法,需要用父类执行 Object.Destroy() 方法才能删除它。
- GameObect.AddComponent<组件名>():添加组件
- Destroy(GameObect.GetComponent<组件名>()):删除组件
示例1:动态添加与删除脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour {
GameObject obj;
void Start () {
obj = GameObject.Find("Cube");
}
void OnGUI()
{
if(GUILayout.Button("添加脚本",GUILayout.Height(50),GUILayout.Width(100)))
{
obj.AddComponent<test>();
}
if(GUILayout.Button("删除脚本",GUILayout.Height(50),GUILayout.Width(100)))
{
Destroy(obj.GetComponent<test>());
}
}
}
测试用来添加的脚本代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class test : MonoBehaviour {
void Start () {
Debug.Log("脚本开始运行!");
}
void OnDestroy()
{
Debug.Log("脚本被销毁!");
}
}
实例2:创建一个立方体对象(Cube),然后为其添加渲染组件,再创建个“Test”脚本组件(只需在Start方法中写一行Debug.Log("内容随意");即可)用来测试脚本组件是否添加成功。
将准备好的贴图赋值给texture变量,其余游戏对象无关紧要。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class E3_04 : MonoBehaviour {
private GameObject obj; //创建游戏对象
private Renderer render; //渲染器
public Texture texture; //贴图
void Start () {
obj = GameObject.Find("Cube"); //获取游戏对象
obj.AddComponent<Test>(); //给当前对象添加一个脚本组件
render = obj.GetComponent<Renderer>(); //获取该对象的渲染器
}
void OnGUI()
{
if(GUILayout.Button("添加颜色",GUILayout.Height(70),GUILayout.Width(120)))
{
//修改渲染器的颜色
render.material.color = Color.green;
//为了避免残留,将贴图置空
render.material.mainTexture = null;
}
if (GUILayout.Button("添加贴图", GUILayout.Height(70), GUILayout.Width(120)))
{
//为了避免残留,将贴图置空
render.material = null;
//添加组件贴图
render.material.mainTexture = texture;
}
}
void Update () {
}
}
运行结果:点击“添加颜色”立方体会变为绿色,点击添加贴图,立方体表面会添加上贴图,下面一行为“Test”脚本打印的文字。