- Home /
Issue within my code (not sure with what exactly)
Can anyone point out what I'm doing wrong here:
using UnityEngine;
using System.Collections;
public class moveTowardsPlayer : MonoBehaviour
{
private Transform target;
float speed = 30.0f; // move speed
private bool magnetBool = false;
void Start()
{
target = GameObject.FindGameObjectWithTag("Player").transform;
}
void Update()
{
magnet ();
}
void magnet()
{
if(GUICounters.magnet == 1 && magnetBool == false)
{
magnetBool = true;
Debug.Log ("here");
transform.position = Vector3.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
StartCoroutine(magnetTimer());
}
}
IEnumerator magnetTimer()
{
yield return new WaitForSeconds(5);
GUICounters.magnet = 0;
magnetBool = false;
Debug.Log ("after coroutine");
}
}
So I want all objects with this script on it to go towards the player when I collect a certain amount of powerups (1 in this case) The problem is, when I collect one, they don't move towards the player, nothing happens.
In the console, when I collect a powerup, the Debug.Log("here")
is displayed 3 times, even though it should only display once as I set the boolean to true inside the if statement.
The Coroutine is so the objects will move towards me for 5 seconds and then reset the counter back to 0 so I can repeat the process the next time I collect a powerup.
As far as I can see, this should work, but the strange behaviour from the console leads me to believe I'm missing something. If anyone could help me out, I'd appreciate it.
Hello, are you sure there's only one object with the script moveTowardsPlayer ? And if you don't call the coroutine does it still keep printing "here"?
Answer by AyAMrau · Sep 04, 2014 at 05:40 PM
Vector3.MoveTowards() has to be called repeatedly if you want the object to continue moving. Because you force the if statement to not execute more than once, then the object will only make one move (which may be very small so you can't see it) and stop.
You should probably make another coroutine that will call the line with MoveTowards every frame and then stop it once the time is up.
As for "here" appearing 3 times, do you have more than one object with this script?
Ah I see, that makes sense. I'll play around and see what I can come up with.
As for the "here" issue, that's my fault, I have multiple powerups and I've been so focused on this one I forgot I attached the script to the others too, that's my bad :P
Your answer
Follow this Question
Related Questions
Assertion Failed? 0 Answers
reset bool on timer passed by ref 1 Answer
Fnaf Rebot, not working with, Door. 1 Answer
Coroutine doesnt turn bool? 0 Answers