unity销毁子弹的三种方式
一、子弹在飞行几秒后消失
代码如下(示例):
void Start()
{
Destroy(gameObject, 3.0f);//表示子弹三秒后被销毁
}
// Update is called once per frame
void Update()
{
}
二、子弹飞出摄像机的视线后被销毁
代码如下(示例):
private void OnBecameInvisible()
{
Destroy(gameObject);
}
三、子弹飞出多少距离后被销毁
代码如下(示例):
public float speed;
public float destoryDistance;
private Rigidbody2D rg2d;
private Vector3 startPos;
// Start is called before the first frame update
void Start()
{
rg2d = GetComponent<Rigidbody2D>();
rg2d.velocity = transform.right * speed;
startPos = transform.position;
}
// Update is called once per frame
void Update()
{
float distance = (transform.position - startPos).sqrMagnitude;
if (distance > destoryDistance)
{
Destroy(gameObject);
}
}