I have an object in my game that, when clicked, causes the player to move toward it. It does this by sending its position to the player's SetTarget function. The player's Move function then heads toward the position.
This is working, but when I duplicate the object and click on it, the player still moves toward the original object's position. When I print debugging statements to the console, it appears that both positions are being calculated, but the original position is the last one and wins out. (I'm using the object's this.transform.position to send the position to the player's SetTarget function.)
Can I not duplicate objects like this and expect the script to work? Do I need to use a prefab? If so, how? I know how to create prefabs but am not sure what I would need to change with the script or other settings when they are created. Thanks.
Here's the code:
public class PotController : MonoBehaviour {
private GameObject chefObject;
void Start () {
chefObject = GameObject.Find ("Chef");
}
void Update() {
if(Input.GetMouseButtonDown(0)){
//print ("pot clicked!");
ChefController chefScript = chefObject.GetComponent<ChefController> ();
print (this.gameObject.transform.position);
chefScript.SetTheTarget (this.gameObject.transform.position);
}
}
}
public class ChefController : MonoBehaviour {
private Vector3 target;
public float speed = 2;
// Use this for initialization
void Start () {
target = this.transform.position;
}
private void MoveTowardsTarget() {
Vector3 targetPosition = new Vector3(0,0,0);
targetPosition = target;
Vector3 currentPosition = this.transform.position;
//check distance to target
if(Vector3.Distance(currentPosition, targetPosition) > 0.4f) {
Vector3 directionOfTravel = targetPosition - currentPosition;
directionOfTravel.Normalize();
this.transform.Translate(
(directionOfTravel.x * speed * Time.deltaTime),
(directionOfTravel.y * speed * Time.deltaTime),
(directionOfTravel.z * speed * Time.deltaTime),
Space.World);
}
}
void Update () {
MoveTowardsTarget ();
}
public void SetTheTarget (Vector3 position){
target = position;
}
}