How to turn an int into a gameobject?

I know that doesn’t make sense and it isnt really descirbing my question, so let me explain.
I’m trying to get a random object to spawn and then move forward to a certain position and stop there.
So, I created a list of 3 prefabs and then randomly selected one of them to be spawned via Instnatiate.
Then for the movement, I created a circle, and are having the objects move forward to the coordinates of the circle.
However, because my objects are Prefabs, only the spawner (an empty) is in the scene, so I attached my script to the spawner.

This is the code script I’ve made.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
public class CarSpawnScript : MonoBehaviour
{
public GameObject Prefab1;
public GameObject Prefab2;
public GameObject Prefab3;
public float speed = 2;
public GameObject waypoint;
private void Start()
{
GameObject[ ] cars = { Prefab1, Prefab2, Prefab3 };
int prefab = Random.Range(0, 3);
Instantiate(cars[prefab], transform.position, Quaternion.identity);
}
private void Update()
{
//car movement upon spawn
Vector3 newPos = Vector3.MoveTowards(transform.position, waypoint.transform.position, speed * Time.deltaTime);
transform.position = newPos;

Independetly, the spawning part and the movement part work. But I don’t know how to move the prefab objects instead of the spawner.

I don’t know C#, so is there a way to assign a varible to cars[prefab] and then use that to replace the Vector3.MoveTowards()?

Or is there a better way?

This is the scene, by the way
9136006--1268812--upload_2023-7-9_22-20-0.png

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

I don’t know what I’m doing so thank you! Learned :stuck_out_tongue:

1 Like