Unity(八):查找指定标签的游戏对象、Invoke、InvokeRepeating、Instantiate

阅读 54

2022-07-14


FindGameObjectsWithTag

Unity(八):查找指定标签的游戏对象、Invoke、InvokeRepeating、Instantiate_unity3d


Unity(八):查找指定标签的游戏对象、Invoke、InvokeRepeating、Instantiate_unity_02

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

Unity(八):查找指定标签的游戏对象、Invoke、InvokeRepeating、Instantiate_ide_03

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秒后销毁游戏对象
}
}

}


精彩评论(0)

0 0 举报