01 创建一个Test脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
private void Awake()
{
Debug.Log("Test Awake");
}
void Start()
{
Debug.Log("Test Start");
}
private void FixedUpdate()
{
}
}
02 Demo脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Demo : MonoBehaviour
{
void Start()
{
//通过gameObject.AddComponent<Test>();将Test脚本动态的加载到本脚本所在的gameObject上
gameObject.AddComponent<Test>();
//通过gameObject.AddComponent<Test>();将Test脚本,通过GameObject.Find方法动态的加载到特定的GameObject上
GameObject.Find("Controller").AddComponent<Test>();
//通过GameObject.Find("Controller").GetComponent<Test>();将Test脚本,通过GameObject.Find方法动态的赋值到特定的GameObject上
Test test = GameObject.Find("Controller").GetComponent<Test>();
}
}
03 运行效果