Hi community,
I got multiple players and I want each of them to move to the points where I clicked with my mouse. But I don’t get it atm, maybe with your help. Here is my script and my inspector.
Controller:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WagonController : MonoBehaviour
{
public GameObject target;
public float speed;
public Vector3 moveToPosition;
public Camera mainCamera;
public List<Vector3> wayPoints;
private int index;
// Start is called before the first frame update
void Start()
{
moveToPosition = transform.position;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.A))
{
StartCoroutine(Move());
}
if(Input.GetMouseButtonDown(0))
{
Vector2 raycastposition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(raycastposition, Vector2.zero);
if(hit.collider != null)
{
if(hit.collider.gameObject.tag == "Player")
{
target = hit.collider.gameObject;
}
}
}
AddPoint();
if(target != null)
{
target.transform.position = Vector3.MoveTowards(target.transform.position, moveToPosition, speed * Time.deltaTime);
}
}
private void AddPoint()
{
if(Input.GetMouseButtonDown(0))
{
moveToPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
moveToPosition.z = transform.position.z;
wayPoints.Add(moveToPosition);
}
}
IEnumerator Move()
{
while (target.transform.position != wayPoints[index])
{
target.transform.position = Vector3.MoveTowards(target.transform.position, wayPoints[index], speed * Time.deltaTime);
yield return null;
}
}
}

And when I select one of my circles, the script switches to the clicked Wagon, and adds a new way point, but when I press “A” my player stops moving.

Here is my problem:
I want to select the player, one of those 3 circles. Then I want to click with my mouse on the map and the clicked player should follow the path I gave him, but not change direction or anything else. He should stop when he is on the last point that I’ve clicked…
I hope it’s understandable…