- Home /
Move towards not working with velocity in script
I have a player with rigidbody set to dynamic. The player jumps on platforms. At some certain time I want the player to move towards a gameobject using Vector3.MoveTowards. But the script doesn't work and gives a object not set to reference error.
Here's the script.
Transform ReviverBox;
Rigidbody2D rb;
void Start () {
ReviverBox = GameObject.FindWithTag("Reviver").transform;
}
void Update () {
if (GameManager.instance.reviveBool)
{
transform.position = Vector3.MoveTowards(transform.position, ReviverBox.position, ReviveSpeed * Time.deltaTime); // this line gives the error.
}
movement = Input.GetAxis("Horizontal") * speed;
}
void FixedUpdate(){
Vector2 velocity = rb.velocity;
velocity.x = movement;
rb.velocity = velocity;
}
Answer by tormentoarmagedoom · Feb 21, 2018 at 12:10 PM
Debug the code.
What reference is missing? The ReviverBox? IF you have "object not set to reference error" most probably is not "Vector3.MoveTowards" problem, is a reference problem.
First, do as tutorail shows, create a float variable to calculate the step before using MoveTowards, and use this 2 debug.log before MoveTowards to check via console if everything is ok.
Debug.Log (ReviverBox.position);
Debug.Log (ReviveSpeed);
This is the error that I'm getting. NullReferenceException: Object reference not set to an instance of an object
When I click on it it takes me to this line
transform.position = Vector3.$$anonymous$$oveTowards(transform.position, ReviverBox.position, ReviveSpeed * Time.deltaTime);
This means when it tries to execute the command, one of the information you give can not be find, is null. Thats why you shoud use the Debug.Log to see which variable is miissing, if is some position, speed, or what.
No problem I just fixed it! I had commented out something that wasn't supposed to be commeneted. Thank You. The above code is working perfect now.
Accept the answer anyway please :D
Answer by dmitriy-untilov · Feb 21, 2018 at 12:16 PM
"object not set to reference error" can be caused by incorrect initialization of ReviverBox
. You can simply define ReviverBox
as public
in your script and drag and drop appropriate GameObject in the UnityEditor. Then you can cache transform value to local variable: var reviverBoxTransform = ReviverBox.transform;
Your answer
Follow this Question
Related Questions
Unity2D - MoveTowards not working as planned 1 Answer
make enemy only follow along the X and Z axis 1 Answer
MoveTowards won't translate on the y axis and lerp leaves character jittering in mid-air 0 Answers
Getting a variable from a specific gameobject for another script 3 Answers
Unexpected behavior on Vector3.moveTowards for Player 0 Answers