Worker who should gather and come back to base script problems

Hello guys,

im rly new to coding with unity but I already have a lot of fun :).

At the moment I write on a “worker-script”, the worker should go from his base to the mine, gather 5 seconds , bring some gold and go back to base and repeat.

I got two issues at the moment:

  • The worker is also waiting 5 seconds at the base, actually I wanted to give him a different waitforseconds of 2 seconds.

  • the +money is gaining every time and not only once in the function, im not able to cut it out the function so just updates once.

I would be rly glad if anyone could help me :).
Thank you and best regards
Rene

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class worker : MonoBehaviour
{
    public float speed = 1f;

    public static int mineWorth;


    public Transform basis;
    public Transform mine;

    private Transform target;
    private Transform _basis;

    private bool backway;
    private bool reachedMine;

    private void Awake()
    {
        transform.position = basis.transform.position;
       target = mine.transform;
        _basis = basis.transform;

        backway = false;
        reachedMine = false;
    }

    void Update()
    {       
        
        if (Vector3.Distance(transform.position, basis.position) < 0.1f)
        {
            backway = false;
        }

        if (!backway )
        {
            float step = speed * Time.deltaTime; 
            transform.position = Vector3.MoveTowards(transform.position, target.position, step);
        }     

        if (Vector3.Distance(transform.position, mine.position) < 0.001f)
        {
            StartCoroutine(Mining());

            reachedMine = true;
        }

        if (reachedMine)
        {

            miningGain();

        }

        if (backway)
        {
            Debug.Log("onBackway");
            float step = speed * Time.deltaTime;
            transform.position = Vector3.MoveTowards(transform.position, basis.position, step);
        }
    }

    IEnumerator Mining()
    {
        Debug.Log("mine reached");
        yield return new WaitForSeconds(5f);
        backway = true;
        Debug.Log("mined");
    }

    void miningGain()
    {
        reachedMine = false;
        PlayerStats.Money += 1;

    }
    
}

Hello.

You are trying to implement a simple AI script. But i see so many code inside Update. Must remeber Update is executed every frame, so if a condition is met, you need make sure, will not be executing all frames while the condition is met. Do some bools to know the exact moment of the process.

Like: GoingToMine, Mining, REturningTobase, AtBase, WithCargo, NoCargo, etc…

As more bools, more control you will have of the code flow.

Debbug your code while running so you can see the state of each variable each frame. Take your time, dont try to go fast.

Good luck"