gameobject teleports to 0, 0, 0 at start

for some reason this code teleports the gameobject it is attached to to 0, 0, 0 at start and I can’t figure out why.

private Zombie Zombie;

    private Rigidbody2D rb;

    [SerializeField] private float MoveSpeed;
    [SerializeField] private float RoamRadius;

    private Vector2 StartPos;
    private Vector2 ToPos;
    private Vector2 CurrentPos;

    void Start()
    { 
        Zombie = GetComponent<Zombie>();
        rb = GetComponent<Rigidbody2D>();

        StartPos = new Vector2(transform.position.x, transform.position.y);
    }

    void FixedUpdate()
    {
        if(Zombie.IsHostile == false)
        {
            transform.position = Vector2.MoveTowards(CurrentPos, ToPos, MoveSpeed * Time.deltaTime);
        }
    }

    void Update()
    {
        if(Zombie.IsHostile == false)
        {
            CurrentPos = new Vector2(transform.position.x, transform.position.y);

            if(CurrentPos == ToPos)
            {
                ToPos = StartPos + (Random.insideUnitCircle * RoamRadius);
            }
        }
    }

Only one line above sets the transform position (line 24).

Print out what you’re feeding into it.

If that’s not where the problem comes from, go look for the script or animation that is doing the position change.

1 Like

Adding CurrentPos = new Vector2(transform.position.x, transform.position.y); at Start() fixed it somehow.

1 Like

Ah, of course… because otherwise CurrentPos would start at zero and slowly move out to where you want it.

2 Likes