Stop object at position after move

I just started learning Unity and C#

I’m trying to move my sprite over a line I draw on-screen with the mouse, it looks like the script is more or less working, but I would like to keep the GameObject at the position it is at the end of the line when it finishes the movement.

As you can see from the picture attached every time it finishes the animation it goes back to its original position (0,0).

How can I stop this behavior?

using System.Collections;
using System.Collections.Generic;
using Unity.Burst.Intrinsics;
using Unity.VisualScripting;
using UnityEngine;

public class Follow : MonoBehaviour
{
    private LineRenderer lineRenderer;
    public GameObject objectToMove;
    public float speed = 5f;

    private Vector3[] positions = new Vector3[397];
    private Vector3[] pos;
    private int index = 0;

    private GameObject toFollow;
    DrawLines drawLines;
    [SerializeField] GameObject gameController;

    private bool isDrawingLineDone = false;
    // Start is called before the first frame update
    void Awake()
    {
        drawLines = gameController.GetComponent<DrawLines>();

    }


    // Update is called once per frame
    void Update()

    {

        if (Input.GetMouseButtonDown(0) == true) // caso linea si e click
        {
            clearLines();

        }



        if (drawLines.isLinePresent == true && Input.GetMouseButtonUp(0) == true)
        {
            if (!isDrawingLineDone)
            {
                pos = GetLinePointsInWorldSpace();
                objectToMove.transform.position = pos[index];

                isDrawingLineDone = true;
            }



        }

        if (isDrawingLineDone == true && finishMove == false)
        {
            Move();
        }
        else if (isDrawingLineDone == true && finishMove == true)
        {
            objectToMove.transform.position = pos[pos.Length - 1];
        }

    }




    Vector3[] GetLinePointsInWorldSpace()
    {
        //Get the positions which are shown in the inspector
        toFollow = GameObject.Find("Linea");
        lineRenderer = toFollow.GetComponent<LineRenderer>();
        lineRenderer.GetPositions(positions);

        //the points returned are in world space
        return positions;
    }

    // MOve the gameObject
    private bool finishMove = false;
    void Move()
    {

        objectToMove.transform.position = Vector3.MoveTowards(objectToMove.transform.position,
                                                pos[index],
                                                speed * Time.deltaTime);

        if (objectToMove.transform.position == pos[index])
        {
            index += 1;

            if (objectToMove.transform.position == pos[pos.Length - 1])
            {
                print("DONE");
                finishMove = true;
               
            }
        }

        if (index == pos.Length)
        {
            index = 0;
        }
    }


    // delete other line if there is
    private GameObject toDestroy;
    void clearLines()
    {
        toDestroy = GameObject.Find("Linea");
        Destroy(toDestroy);
        drawLines.isLinePresent = false;
    }
}

8483837--1128128--R0qqM.gif

I would debug the code or add some more “print” to see what happens when and also what position is the next in the array that Move() is using.
When does the “DONE” get printed in the console? At the end of the line or when the ball is back at zero?
Can you also post the DrawLines class? I cant find where isLinePresent is set to true.
You have many variables in the code that control the flow like finishMove, isDrawingLineDone… it is not uncommon to get a bug if you need to check all the combinations of them.

Line 91 compares floating points… you want to avoid that.

Floating (float) point imprecision:

Never test floating point (float) quantities for equality / inequality. Here’s why:

https://starmanta.gitbooks.io/unitytipsredux/content/floating-point.html

https://discussions.unity.com/t/851400/4

https://discussions.unity.com/t/843503/4

Also, line 114 you are violating this rule:

Remember the first rule of GameObject.Find():

Do not use GameObject.Find();

More information: https://starmanta.gitbooks.io/unitytipsredux/content/first-question.html

Whatever it is, you must find a way to get the information you need in order to reason about what the problem is.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: https://discussions.unity.com/t/700551 or this answer for Android: https://discussions.unity.com/t/699654

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

https://discussions.unity.com/t/839300/3

When in doubt, print it out!™

Note: the print() function is an alias for Debug.Log() provided by the MonoBehaviour class.

Don’t use Magic Numbers:

https://discussions.unity.com/t/846897/4

Instead, know where the number comes from and compute it from the correct inputs.