下面演示如何在 Unity 中通过代码动态添加和移除脚本组件。示例里先调用 AddComponent 把 script_new 挂到当前 gameObject 上,再通过 Invoke 延迟 1 秒触发销毁逻辑,用 Destroy 移除刚才添加的脚本组件。
调用方示例
...
void Start () {
gameObject.AddComponent("script_new");//添加脚本组件
Invoke("delete11", 1);
}
void delete11()
{
Destroy(gameObject.GetComponent("script_new"), 1); // 销毁脚本组件
}
script_new.cs
被动态添加的脚本本身是一个普通的 MonoBehaviour。它在 Start 时打印 new,在 OnDestroy 时打印 destory,用于观察生命周期是否按预期被触发。
..
using UnityEngine;
using System.Collections;
public class script_new : MonoBehaviour {
// Use this for initialization
void Start () {
print("new");
}
// Update is called once per frame
void Update () {
}
void OnDestroy()
{
print("destory");
}
}