步驟: 碰撞後複製產生原物件
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CopyObject : MonoBehaviour {
//public GameObject copyGameObject;//要被複製的物件
public GameObject superGameObject;//要被放置在哪個物件底下
private GameObject childGameObject;//被複製出來的物件
private void OnCollisionEnter (Collision other)
{
if (other.gameObject.tag == "cube")
{
Debug.Log("collide");
copyObjects();
}
}
public void copyObjects()
{
childGameObject = Instantiate(gameObject);//複製copyGameObject物件(連同該物件身上的腳本一起複製)
childGameObject.transform.parent = superGameObject.transform;//放到superGameObject物件內
childGameObject.transform.position = new Vector3(gameObject.transform.position.x, Random.Range(0.5f,8), gameObject.transform.position.z);
//childGameObject.transform.position = new Vector3(GetRandomCoordinate(),Random.Range(0.5f,2), GetRandomCoordinate());
childGameObject.name = "ChildBall";
Debug.Log("copy");
}
private float GetRandomCoordinate(){
var coordinate = Random.Range(-7,7);
while (coordinate > -1.5 && coordinate < 1.5)
{
coordinate = Random.Range(-5,5);
}
return coordinate;
}
}