如何不断克隆预制件最有效的方法?如何销毁它?

问题描述 投票:-1回答:1

我有一个克隆的预制物体(例如子弹,球等)。它是由一定间隔时间触发的。我应该在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);
}
c# unity3d game-engine unityscript
1个回答
0
投票

这是一个可能的解决方案。您也可以使用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
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.