Hello, I’m making a missile asset that can lock on to targets, it works fine but I’m having a problem figuring out how to fire an array of missiles at different times e.g. all 6 at once but with a second gap between each missile or all 6 individually at the press of a button.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Missle : MonoBehaviour
{
public GameObject explosionEffect;
public Rigidbody Rb;
public Transform target;
[SerializeField]
bool Chase;
[SerializeField]
bool Eject;
public FixedJoint FJ;
public float turn;
public float rocketVelocity;
float accel = 3;
// Start is called before the first frame update
void Start()
{
Rb.GetComponent<Rigidbody>();
}
// Update is called once per frame
void FixedUpdate()
{
//initiate rocket
if (Input.GetKey("u") && Chase == false && Eject == false)
{
Ejected();
}
if (Input.GetKey("i"))
{
Explode();
}
// fire away from floor
if (Eject == true)
{
Rb.velocity = transform.forward * 10f;
}
//lock on to target and chase
if (Chase == true)
{
Rb.velocity = transform.forward * rocketVelocity;
var rocketTargetRotation = Quaternion.LookRotation(target.position - transform.position);
Rb.MoveRotation(Quaternion.RotateTowards(transform.rotation, rocketTargetRotation, turn));
}
}
// Start the Eject sequence and call countdown for the rockets lock on
void Ejected()
{
Eject = true;
Fired();
}
//once the timer is over call the chase sequence to get the target and chase it.
void Fired() { StartCoroutine(CountTillChase()); }
IEnumerator CountTillChase()
{
yield return new WaitForSeconds(1);
Eject = false;
yield return new WaitForSeconds(1);
Chase = true;
// Code here will be executed after 3 secs
//Do stuff here
}
//Oncollision in the Chase stage call the explosion method
private void OnTriggerEnter(Collider other)
{
if (Chase)
Explode();
}
//Spawns particle effect and destroys the object whilst applying force to nearby rigid bodies
void Explode()
{
Instantiate(explosionEffect, transform.position, transform.rotation);
Collider[] colliders = Physics.OverlapSphere(transform.position, 10);
foreach (Collider nearByObjects in colliders)
{
Rigidbody ERB = nearByObjects.GetComponent<Rigidbody>();
if (ERB != null)
{
Rb.AddExplosionForce(10000, transform.position, 10000);
}
}
Destroy(gameObject);
}
}