i want a script that spawn objects around a sphere
LMGTFY - Let Me Google That For You have a look at the link…
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour {
public int numObjects = 10;
public GameObject prefab;
void Start() {
Vector3 center = transform.position;
for (int i = 0; i < numObjects; i++){
Vector3 pos = RandomCircle(center, 5.0f);
Quaternion rot = Quaternion.FromToRotation(Vector3.forward, center-pos);
Instantiate(prefab, pos, rot);
}
}
Vector3 RandomCircle ( Vector3 center , float radius ){
float ang = Random.value * 360;
Vector3 pos;
pos.x = center.x + radius * Mathf.Sin(ang * Mathf.Deg2Rad);
pos.y = center.y + radius * Mathf.Cos(ang * Mathf.Deg2Rad);
pos.z = center.z;
return pos;
}
}
Alternative solution that uses the Random.onUnitSphere
method. IMO Random.onUnitSphere * radius
is more readable than math even though the math described above is definitely not complicated. YMMV.
public class PositionOnSphere: MonoBehaviour {
public SphereCollider sphereCollider;
private bool _active;
private void OnValidate() => _active = sphereCollider != default;
private void Start() {
// As an example, just position the gameObject that this example component is attached to
PositionSpawnedOnSphereCollider(gameObject);
}
private void PositionSpawnedOnSphereCollider(GameObject targetGameObject)
{
if (!_active) return;
var positionOutsideSphere = Random.onUnitSphere * sphereCollider.radius;
targetGameObject.transform.position = positionOutsideSphere;
}
}