- Home /
Function is not updating the variable
Here is a very simple script in which when variable "move" is true, I want to move the gameobject to "target" location.
public class Truck : MonoBehaviour
{
private bool move;
Vector3 target;
float closeProximityDistance = 1.0f;
float speed = 1.0f;
void Start()
{
move = false; }
void Update()
{
if (move)
{
if (Vector3.Distance(this.transform.position, target) > closeProximityDistance)
{
transform.position = Vector3.MoveTowards(transform.position, target, Time.deltaTime * speed);
}
else
{
Debug.Log("Reached the position");
move = false;
}
}
}
public void moveTo(Vector3 shopCoords)
{
target = shopCoords;
move = true;
}
}
moveTo() updates the 'target' and 'move' variables. moveTo() function is being called from different script when any button is pressed. Also note that when that button is pressed, after that Truck gameobject is instantiated
The problem is game object doesn't move because "move" is false even after the moveTo() is called. How to solve this?
,
Answer by GrayLightGames · Nov 01, 2019 at 07:03 AM
I recommend that if you find your program is following a code path you don't intend, use Debug.Log statements to check all the values being compared in the suspect if statement. Seeing values at the moment the strange behavior is occurring can often make it more apparent what is wrong. Let us know if that helps, hope it does!
The results of Debug.Log were very weird. First, I changed the Start() to Awake() because moveTo() function was getting called before the Start().
public void moveTo(Vector3 shopCoords)
{
Debug.Log(move);
target = shopCoords;
move = true;
Debug.Log(move);
}
Both debugs are giving "true". Now, I also made Start function and put Debug.Log there and it was giving "false". I was not able to understand what was happening so I changed how the function is called so that moveTo() function is called after the Start(), now it works fine.
$$anonymous$$y bad, I was completely wrong... it should be greater than. If $$anonymous$$oveTo is on a button it shouldn't be called before Start... was your object inactive before the button is pressed? Either way if you found a solution its probably good to separate your comment into an answer and accept it so everyone knows it is resolved. I'll update my answer to avoid confusion. Good luck with your project!
Your answer
Follow this Question
Related Questions
Can I use GetComponents reference outside Of awake and start functions 1 Answer
How to change UI image with a name to a different image with a name 2 Answers
Bool function not running when called from other script 2 Answers
How to tell an operand "Once" or "Started to" 3 Answers
Multiple Cars not working 1 Answer