- Home /
How to get a constantly updating variable to a non-constantly updated function.
I have a script that is used for player combat, in which pressing different buttons calls on different functions and coroutines that instantiate projectiles from the players position. However, I am struggling to find a way to constantly update the player's position inside these functions/coroutines since they're only being run once. Here's an example:
void Update () {
Vector2 player = new Vector2(transform.position.x, transform.position.y);
if (Input.GetKeyDown(KeyCode.R)) {
StartCoroutine(RapidShoot(1, player));
}
}
IEnumerator RapidShoot (float rapidShootTime, Vector2 player) {
while (rapidShootTime > 0) {
rapidShootTime -= Time.deltaTime;
GameObject newBullet = Instantiate(bullet, player, Quaternion.identity);
newBullet.transform.SetParent(gameObject.transform, true);
yield return new WaitForSeconds(.05f);
}
}
I would appreciate any help possible, thanks!
Answer by Vega4Life · Dec 03, 2018 at 12:15 AM
You don't need to reference the position in Update() as you already have it through transform.position. Just do this:
void Update()
{
if (Input.GetKeyDown(KeyCode.R))
{
StartCoroutine(RapidShoot(1));
}
}
IEnumerator RapidShoot(float rapidShootTime)
{
while (rapidShootTime > 0)
{
rapidShootTime -= Time.deltaTime;
Vector2 playerPosition = new Vector2(transform.position.x, transform.position.y);
GameObject newBullet = Instantiate(bullet, playerPosition, Quaternion.identity);
newBullet.transform.SetParent(gameObject.transform, true);
yield return new WaitForSeconds(.05f);
}
}
Ah. $$anonymous$$istakes like these re$$anonymous$$d me that I'm still a beginner with lots to learn. Thanks so much.
Your answer
Follow this Question
Related Questions
unity 2D with delay run and jump 0 Answers
Having trouble with Position X location on objects 0 Answers
Canvas Element become small on simulator 0 Answers
Problem with Coroutines and waitforseconds. 1 Answer
Can I upgrade my license? 0 Answers