FindGameObjectsWithTag
public class FindTags : MonoBehaviour
{
public GameObject[] cubes;
void Start()
{
cubes = GameObject.FindGameObjectsWithTag("Player");
foreach (var obj in cubes)
Debug.Log(obj.name);
}
}
Invoke
InvokeRepeating
public class InvokeAndInvokeRepeating : MonoBehaviour
{
public GameObject target;
void Start()
{
// 2秒后执行函数
Invoke("SpawnObject", 2);
// 5秒后执行函数,往后每隔3秒执行一次函数
InvokeRepeating("SpawnObject", 5, 3);
}
void SpawnObject()
{
float x = Random.Range(-2.0f, 2.0f);
float z = Random.Range(-2.0f, 2.0f);
// 克隆游戏对象
Instantiate(target, new Vector3(x, 2, z), Quaternion.identity);
}
}
Instantiate
public class UsingInstantiate : MonoBehaviour
{
public GameObject cubePrefab;
void Update ()
{
if(Input.GetKeyDown(KeyCode.Space))
{
GameObject rocketInstance = Instantiate(cubePrefab, cubePrefab.transform.position, cubePrefab.transform.rotation);
rocketInstance.GetComponent<Rigidbody>().AddForce(cubePrefab.transform.forward * 5000); // 提供力
Destroy(rocketInstance, 1.5f); // 1.5秒后销毁游戏对象
}
}
}