how to make % posibility to spawn an object C# in unity code example
Example 1: how to make % posibility to spawn an object in unity
if(Random.value > 0.5) //%50 percent chance {//code here } if(Random.value > 0.2) //%80 percent chance (1 - 0.2 is 0.8) { //code here } if(Random.value > 0.7) //%30 percent chance (1 - 0.7 is 0.3) { //code here }
Example 2: how to make % posibility to spawn an object C# in unity
public class RandomTimeSpawner : MonoBehaviour { //Spawn this object public GameObject spawnObject; public float maxTime = 5; public float minTime = 2; //current time private float time; //The time to spawn the object private float spawnTime; void Start(){ SetRandomTime(); time = minTime; } void FixedUpdate(){ //Counts up time += Time.deltaTime; //Check if its the right time to spawn the object if(time >= spawnTime){ SpawnObject(); SetRandomTime(); } } //Spawns the object and resets the time void SpawnObject(){ time = minTime; Instantiate (spawnObject, transform.position, spawnObject.transform.rotation); } //Sets the random time between minTime and maxTime void SetRandomTime(){ spawnTime = Random.Range(minTime, maxTime); } }