Firstly, how to post code tags: Using code tags properly
Instantiate returns the newly created instance. You can use this to modify it after its been created, and hold onto a reference to it for as long as you need.
So for example:
public class CarSpawnScript : MonoBehaviour
{
public GameObject[] carPrefabs;
public float speed = 2;
public Transform waypoint;
private GameObject carInstance;
private void Start()
{
int prefabCount = carPrefabs.Length;
int index = Random.Range(0, prefabCount);
GameObject prefab = carPrefabs[index];
carInstance = Instantiate(prefab, transform.position, Quaternion.identity);
}
private void Update()
{
Vector3 currentPosition = carInstance.transform.position;
Vector3 newPos = Vector3.MoveTowards(currentPosition, waypoint.position, speed * Time.deltaTime);
carInstance.transform.position = newPos;
}
}
Few things I adjusted and will point out:
- We store our prefabs in an array, which we can assign to via the inspector
- We use the length of the array to not have to hard code a random index
- Then we hold onto the instanced car so we can use it between Start and Update, and move said instance