Unity random mesh spawner at certain position C# script

In this blog post I will share a simple script that I’ve made to randomize what game object to be instantiated at a certain position as a child game object.

For example, a car game object needs random accessories to be instantiated at certain area of the car… bla bla bla.

This is the script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RandomMeshSpawner : MonoBehaviour
{
	
	public List<GameObject> meshes;
	public Transform refTransform;
	
    // Start is called before the first frame update
    void Start()
    {
        GameObject omesh = Instantiate(meshes[Random.Range(0, meshes.Count-1)]) as GameObject;
		omesh.transform.SetParent(gameObject.transform, false);
		omesh.transform.localPosition = refTransform.localPosition;
		omesh.transform.localScale = refTransform.localScale;
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

How to use the script? Check out my video below:

Leave a Reply

Your email address will not be published. Required fields are marked *