- Home /
Question by
EvanCheddar · Oct 25, 2018 at 02:55 AM ·
instantiateprefabmoving platform
How to Instantiate objects randomly within the space of another moving object?
I have a moving object and I want to instantiate a prefab randomly within the space of the moving object. Not sure how to achieve this with Random.Range. Thank you.
Comment
Best Answer
Answer by michi_b · Oct 25, 2018 at 06:18 AM
If by "within the space" you mean inside a certain radius around another object, you can use Random.insideUnitSphere for that. Multiply this random position with the radius you want to use, then add it to the position of your moving object.
Hey thanks for replying, can you possibly give me an example of how to use this?
If you attach this script to a moving game object, for example, and assign a prefab to instantiate to it in the inspector, it will start instantiating the prefab randomly around itself
using UnityEngine;
using System.Collections;
public class Spawner : $$anonymous$$onoBehaviour
{
public GameObject prefabToInstantiate;
public float maxDistance = 1f;
public float spawnInterval = 1f;
IEnumerator Start()
{
while(true)
{
Vector3 currentPosition = transform.position;
Vector3 randomOffset = Random.insideUnitSphere * maxDistance;
Vector3 spawnPosition = currentPosition + randomOffset;
Instantiate(prefabToInstantiate, spawnPosition, Random.rotation);
yield return new WaitForSeconds(spawnInterval);
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612180917im_/https://answers.unity.com/themes/thub/images/avi.jpg)