Help with Instantiating a prefab in C#

I am implementing some code for a RTS game. I want to spawn units from a building. I have this portion working, but when if I create multiple units, they spawn on top of each other. I want to somehow detect if something is in the way, if so move the spawn location. I tried to do a RayCast, but I’m pretty new at Unity so its not working right. Can someone help me out? BTW the code below is after about 50 trys, so no laughing at how wrong it is. :slight_smile:

Vector3 SpawnPoint = new Vector3(0,1,0);
RaycastHit hit;
Ray r = Camera.main.ScreenPointToRay(SpawnPoint);
if(Physics.Raycast(r,out hit))
if(hit.rigidbody != null hit.rigidbody.CompareTag(“ground”))
SpawnPoint.x+=5;

Instantiate(marine, SpawnPoint, Quaternion.identity);

Instantiate your prefab with a disabled mesh renderer. (So it is not visible).

Then do a Collision test on the prefab, if there is a collision that matches a tag (such as building or other object you don’t want to instantiate over), either keep moving the prefab around until there are no collisions, or instantiate it at a specific place.

How can I grab the prefab that was just created to do collision test?

// Instantiate it…

GameObject instantiatedPrefab = GameObject.Instantiate(_yourPrefab);

// Reference the script on your prefab

MyScript myScript = instantiatedPrefab.GetComponent<MyScript>();
if(myScript.CheckBuildingCollision())
 // Write code here if there is a building collision.. i.e move prefab somewhere else..

Thanks, thats exactly what I needed