Unity2D C# Randomly Spawn GameObject in an Area over another GameObject
I'm new to Unity2D (Unity 5.0.2f1) and have been searching for a solution which I'm sure is staring me in the face!
I have a game object (essentially a road) like below (DirtTrack1):

I have a spawner which spawns GameObjects (vehicles). I want to spawn those vehicles over this road.
I have tried the following code to do this, essentially trying to spawn the vehicle within the Y-axis area of the road by getting the bottom Y co-ordinate of the road and the top Y co-ordinate, so I get the min and max vertical positions of where I can place the vehicle:
 void FixedUpdate() {
     // Repeat spawning after the period spawn
     // route has finished.
     if (!_inSpawningIteration)
         StartCoroutine (SpawnVehiclePeriodically());
 }
 IEnumerator SpawnVehiclePeriodically()     
 {
     // Get the max and min Y of the road
     float roadY = roadObject.transform.localPosition.y;
     float roadHalfHeight = roadObject.GetComponent<SpriteRenderer>().sprite.bounds.size.y / 2f;
     float roadMaxY = roadY + roadHalfHeight;
     float roadMinY = roadY - roadHalfHeight;
     // Pick a vehicle from the vehicle's array.
     // Then, spawn the vehicle within this Y region
     GameObject vehiclePreFab = _vehicles [random];
     // Randomize the Y position that the vehicle will enter at.
     float randomY = Random.Range (roadMinY, roadMaxY);
     // Set the position and spawn.
     Vector3 newPosition = new Vector3 (Const_RoadItemsPositionX, randomY, 0f);
     GameObject vehicle = (GameObject)GameObject.Instantiate (vehiclePreFab, newPosition, Quaternion.identity);
 }
 
               This does spawn randomly but most times it is always not within the road itself. It is either part on the road or at the outside edge of it.
I can't figure out what I'm doing wrong here but I'm sure it is something very simple!
Answer by UnityCoach · Feb 18, 2017 at 08:14 AM
Hi, roadY is made from the roadObject.localPosition.y, but when you use Instantiate (), it expects a world position. So you have to put it back in the road object's coordinates. Try this :
 newPosition = roadObject.transform.TransformPoint (newPosition);
 
              Your answer