Spawn using Physics.RayCast (for Unity)

Random spawn of objects above the ground using Physics.RayCast.
A simple script with which you can spawn objects, opponents, etc. exactly above the ground at a given height (the ground may not be flat).



// Nicholas Veselov - https://nvjob.github.io using UnityEngine; public class Spawn : MonoBehaviour { public GameObject enemy; public float radiusSpawn = 10; public int numOfBasicEnemies = 10; public float heightAboveGround = 2.0f; public LayerMask groundLayer; Transform tr; RaycastHit hit; void Awake() { tr = transform; } void Start() { for (int i = 0; i < numOfBasicEnemies; i++) { Vector2 randomCircle = Random.insideUnitCircle * radiusSpawn; Vector3 v3rc = new Vector3(tr.position.x + randomCircle.x, 100, tr.position.z + randomCircle.y); if (Physics.Raycast(v3rc, Vector3.down, out hit, 150, groundLayer)) { GameObject enemyRay = Instantiate(enemy); enemyRay.transform.SetPositionAndRotation(new Vector3(v3rc.x, hit.point.y + heightAboveGround, v3rc.z), tr.rotation); enemyRay.transform.parent = tr; } } } }
(C) Copyright 2016 #NVJOB. Contact: nvjob.dev@gmail.com
Nicholas Veselov Unity Game Developer
Николай Веселов Unity Разработчик Санкт-Петербург