I have found a script which does partially what I want to accomplish. And that is to spawn a prefab along the X axis of a cube or line or whatever. I created a Game Object, dragged a cube in it as its child and attached the following script.
using UnityEngine;
using System.Collections;
public class ObjectSpawn : MonoBehaviour
{
public float minTime = 5f;
public float maxTime = 10f;
public float minX = -5.5f;
public float maxX = 5.5f;
public float topY = 5.5f;
public float z = 0.0f;
public int count = 200;
public GameObject prefab;
public bool doSpawn = true;
void Start()
{
StartCoroutine(Spawner());
}
IEnumerator Spawner()
{
while (doSpawn && count > 0)
{
Vector3 v12 = new Vector3(Random.Range(0, this.gameObject.transform.position.x), 0, 0);
// Vector3 v = new Vector3(Random.Range(minX, maxX), topY, z);
Instantiate(prefab, v12, Random.rotation);
count–;
yield return new WaitForSeconds(Random.Range(minTime, maxTime));
}
}
}
As you can see, I commented the line with a minX,maxX and im attempting to get a range from 0 to the X of the cube whatever that might be.
Despite that my prefab only seems to spawn from two locations or an extremely small range, not the entire length of the Object.


Not really bounds, if you look at my image, I have a bar and spheres are forming a little bit above the bar and falling, so far I have three spheres falling. However all of the spheres spawned is coming from a really small range where as i want it to spawn along the length of the bar.
Vector3 v12 = new Vector3(Random.Range(0, this.gameObject.transform.position.x), 0, 0);
Just fyi, “gameObject” on its own always refers to “this” so you don’t need to include “this”.
You’re getting a world position between the origin x=0, and the gameObject’s X position. Looking at your screenshot, the only way that could work is if one side of your bar object is sitting on the origin, and the other side is where the object’s pivot is. It’s very likely that your bar is positioned around its center, which is probably very close to the origin and therefore your code has a very small range to choose from.
Try using Debug.Log to print out the range that your function is choosing from.
What @boxhallowed is saying is that you should choose a location between the left-most extents of the bar, and the right-most extents of the bar, which can be done like this:
Renderer renderer = GetComponent<Renderer>();
float min = renderer.bounds.min.x;
float max = renderer.bounds.max.x;
Vector3 v12 = new Vector3(Random.Range(min, max), 0, 0);