我有一个克隆的预制物体(例如子弹,球等)。它是由一定间隔时间触发的。我应该在Awake()
或Update()
方法中使用吗?哪一个便宜?有没有更有效的克隆方法?
而且我知道要销毁对象,但是当它到达屏幕末端(或特定坐标)时,我应该如何销毁该对象?
private void shoot() {
var clone = Instantiate(bulletPrefab);
// set to right of the launcher
var position = transform.position;
clone.transform.position = new Vector2(position.x + 0.5f, position.y);
}
private void Awake() {
InvokeRepeating("shoot", mTime, mFireRate);
}
这是一个可能的解决方案。您也可以使用Coroutines执行重复操作。
public class Shooter: MonoBehaviour
{
public float timeBetweenShots = 1.5f;
public GameObject bulletPrefab;
public Transform bulletStartLocation;
private spawnCooldown = 0f;
void Update ()
{
spawnCooldown += Time.deltaTime;
if (spawnCooldown >= timeBetweenShots)
{
Instantiate(
bulletPrefab,
bulletStartLocation.position,
bulletStartLocation.rotation
);
spawnCooldown = 0f;
}
}
}
public class Bullet: MonoBehaviour
{
private Transform dieCoordinates;
void Start ()
{
dieCoordinates = GameObject.FindWithTag("Finish").transform;
}
void Update ()
{
if (Vector3.Distance(transform.position, dieCoordinates) < 0.5f)
{
Destroy(gameObject);
}
}
void FixedUpdate ()
{
// TODO: implement the projectile movement
}
}