Add "speed" to an object every X seconds
Hello everyone, my question is simple, I have this script that moves blocks at a certain speed and destroys them as you can see in the script (and I have other script that spawns this blocks) and I want that this variable:
public float movementSpeed = 10f;
to be more every X seconds, for example, every 10 seconds add 1 to the variable, so the speed of the objects is 11, and every other 10 seconds add another 1 to the variable so it is 12, and so on, but if I add a Coroutine and new objects are spawned they always have 10 in the variable, I want it to be like a "universal" variable so the new objects spawned have the "new" speed... I have no idea how to do it maybe it's very simple but if anyone could help me it would be appreciated. thanks and sorry for bad english, here's the script:
using UnityEngine;
using System.Collections;
public class Block : MonoBehaviour {
public float movementSpeed = 10f;
void Start ()
{
}
// Update is called once per frame
void Update () {
transform.Translate(Vector3.down * movementSpeed * Time.deltaTime);
if (transform.position.y < -2f)
{
Destroy(gameObject);
}
}
}
Answer by RonnieThePotatoDEV · Jun 11, 2017 at 01:12 AM
Use InvokeRepeating. It just lets you repeat a function over and over again. It has three parameters. The first is the function it is repeating (in your case it will be a function that will be increasing the variable), the second one is after how many seconds will this start repeating. And the third one is how often it repeats. For example:
public float movementSpeed = 10f;
void increaseSpeed ()
{
movementSpeed = movementSpeed + 1f;
}
void Start()
{
InvokeRepeating("increaseSpeed", 5f, 10f);
}
What this does it that it first makes a function, "increaseSpeed", and then when the game starts it waits five seconds, then it repeats that function every ten seconds
This will help more: https://docs.unity3d.com/ScriptReference/MonoBehaviour.InvokeRepeating.html
Hope it helps -Ronnie
Answer by evanwatarai · May 31, 2020 at 08:23 PM
Sorry for asking this question after so long. The code you gave worked for me as well, but is there a way to cap the speed? Thanks so much! @RonnieThePotatoDEV
If you mean by making the speed increase stop after it reaches a certain point then just add a if statement
public float movementSpeed = 10f;
void increaseSpeed ()
{
movementSpeed = movementSpeed + 1f;
}
void Start()
{
InvokeRepeating("increaseSpeed", 5f, 10f);
}
void Update()
{
if (movementSpeed >= 50f)
{
CancelInvoke("increaseSpeed");
}
}
again I don't know if this is the best way, but it gets the job done
Your answer
Follow this Question
Related Questions
Hexagonal Grid Rangefinding 1 Answer
Player won't stop moving when key is released 1 Answer
iOS moving up and down question ( code problem ) 0 Answers
GameObject not looking at me.. 1 Answer
how to move only one object ? 1 Answer