- Home /
Question by
Nicolas4677 · May 26, 2018 at 02:16 AM ·
c#unity 5scripting beginner
Instantiate an object each time in less time
Hi, what I want to do is instantiate an object each time in less time, so it should start with a time between each instantiation of 3 sec, and then when the object collides with other object, the time before the next instantiation is 2.8 sec, an then if that new game object collides again with the other game object, it should be 2.6, all that over and over. Thanks for the help.
This is wat I have:
public GameObject madera;
public GameObject piedra;
public bool destruido = false;
private float time = 3f;
public GameObject player;
private EstadisticasJugador estadisticas;
public int altura = 11;
void Start ()
{
estadisticas = player.GetComponent<EstadisticasJugador>();
InvokeRepeating("Aparicion", time, time);
}
void Update ()
{
if (destruido || estadisticas.colision == true)
{
time-= 0.2f;
}
}
void Aparicion()
{
if(estadisticas.muerto == false)
{
Vector3 position = new Vector3(Random.Range(-6, 6), altura, 0);
Instantiate(madera, position, Quaternion.identity);
Debug.Log("Madera desplegada");
Vector3 position01 = new Vector3(Random.Range(-6, 6), altura, 0);
Instantiate(piedra, position01, Quaternion.identity);
Debug.Log("Madera desplegada");
}
}
Comment
Best Answer
Answer by Temseii · May 26, 2018 at 08:03 AM
float instantiationTimer = 3f;
private void OnCollisionEnter(Collision collision) {
StartCoroutine(CollisionRoutine());
}
IEnumerator CollisionRoutine() {
float decreaseAmount = 0.2f;
yield return new WaitForSeconds(instantiationTimer);
instantiationTimer -= decreaseAmount;
}
Answer by NoDumbQuestion · May 26, 2018 at 02:41 AM
1st of all: please use English when you naming variables because it is more standard and more people can help you when post a question like this.
And, what you want is Couroutine. It is a wait and do function made by Unity based in C#.
void OnColliderEnter()
{
// When collide with some object
StartCoroutine(InstaniateObjectWhenCollide());
}
IEnumerator InstaniateObjectWhenCollide()
{
print("Starting " + Time.time);
yield return new WaitForSeconds(3f);
// DO your instantiate here
print("Done " + Time.time);
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612163433im_/https://answers.unity.com/themes/thub/images/avi.jpg)