Hello there! Just messing around with Unity3d today and testing some things out.
I’m trying to make a simple script where an object (Woodcutter) will detect a tree within a certain range and then move from its position to the tree. This is what I got so far. https://pastebin.com/ZdrS5kHv - It starts working, looks for a tree, finds a tree, but when I expect it to move there using Lerp nothing happens. Not sure why this is. Hope someone can explain it to me
Thanks.
Your move script is called only while the woodcutter is not working and when a tree is found. So when it’s changed to working, the move script can no-longer be called.
1 Like
Yeah I eventually figured it out and got the script working and improved it a bit.
Now it works as expected, returns the wood to home and starts searching for a new tree nearby. Just gotta make a forester now to make sure new trees eventually pop up 
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WoodCutterDetector : MonoBehaviour
{
public GameObject home;
private GameObject tree;
bool working = false;
bool carryingTree = false;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if (working)
{
if(!carryingTree) {
MoveToTree(tree);
} else {
MoveHome ();
}
} else {
GetTreeInRange();
}
}
void MoveHome() {
Vector3 homePosition = home.transform.position;
Vector3 workerPosition = transform.position;
transform.position = Vector3.Lerp(workerPosition, homePosition, 0.1f);
if (Vector3.Distance(homePosition, workerPosition) <= 0.1f)
{
working = false;
carryingTree = false;
}
}
void MoveToTree(GameObject tree)
{
Vector3 treePosition = tree.transform.position;
Vector3 workerPosition = transform.position;
transform.position = Vector3.Lerp(workerPosition, treePosition, 0.1f);
if (Vector3.Distance(treePosition, workerPosition) <= 0.1f)
{
Destroy(tree);
tree = null;
carryingTree = true;
}
}
void GetTreeInRange()
{
GameObject[] trees = GameObject.FindGameObjectsWithTag("Tree");
foreach (GameObject t in trees)
{
float distance = Vector3.Distance(t.transform.position, transform.position);
if (distance <= 5f)
{
tree = t;
working = true;
return;
}
}
}
}
Also have to improve the GetTreeInRange function a bit, so it looks for the closest, but that’s small details. Thanks for your answer 