Tanoda
SpawnBalls.cs
Go to the documentation of this file.
1/******************************************************************************
2 * Copyright (C) Ultraleap, Inc. 2011-2020. *
3 * *
4 * Use subject to the terms of the Apache License 2.0 available at *
5 * http://www.apache.org/licenses/LICENSE-2.0, or another agreement *
6 * between Ultraleap and you, your company or other organization. *
7 ******************************************************************************/
8
9using UnityEngine;
10using System.Collections;
11
12public class SpawnBalls : MonoBehaviour {
13 public GameObject BallPrefab;
14 public float delayInterval = .15f; // seconds
15 public int BallLimit = 100;
16 public Vector3 BallSize = new Vector3(0.1f, 0.1f, 0.1f);
17
18 private IEnumerator _spawnCoroutine;
19
20 void Awake () {
21 _spawnCoroutine = AddBallWithDelay(BallPrefab);
22 }
23
24 public void StartBalls(){
25 StartCoroutine(_spawnCoroutine);
26 }
27
28 public void StopBalls(){
29 StopAllCoroutines();
30 }
31
32 private IEnumerator AddBallWithDelay (GameObject prefab) {
33 while (true) {
34 addBall(prefab);
35 yield return new WaitForSeconds(delayInterval);
36 }
37 }
38
39 private void addBall (GameObject prefab) {
40 if (transform.childCount > BallLimit) removeBalls(BallLimit / 10);
41 GameObject go = GameObject.Instantiate(prefab);
42 go.transform.parent = transform;
43 go.transform.localPosition = Vector3.zero;
44 go.transform.localScale = BallSize;
45 Rigidbody rb = go.GetComponent<Rigidbody>();
46 rb.AddForce(Random.value * 3, -Random.value * 13, Random.value * 3, ForceMode.Impulse);
47 }
48
49 private void removeBalls (int count) {
50 if (count > transform.childCount) count = transform.childCount;
51 for (int b = 0; b < count; b++) {
52 Destroy(transform.GetChild(b).gameObject);
53 }
54 }
55}
UnityEngine.Random Random
Vector3 BallSize
Definition: SpawnBalls.cs:16
int BallLimit
Definition: SpawnBalls.cs:15
float delayInterval
Definition: SpawnBalls.cs:14
void StopBalls()
Definition: SpawnBalls.cs:28
void StartBalls()
Definition: SpawnBalls.cs:24
GameObject BallPrefab
Definition: SpawnBalls.cs:13