Neodroid  0.2.0
Machine Learning Environment Prototyping Tool
ObjectSpawnerConfigurable.cs
Go to the documentation of this file.
1 using System.Collections.Generic;
4 using UnityEngine;
5 
6 namespace droid.Runtime.Prototyping.Configurables {
10  [AddComponentMenu(ConfigurableComponentMenuPath._ComponentMenuPath
11  + "ObjectSpawner"
12  + ConfigurableComponentMenuPath._Postfix)]
14  [SerializeField] int _amount = 0;
15 
16  [SerializeField] Axis _axis = Axis.X_;
17 
18  [SerializeField] GameObject _object_to_spawn = null;
19 
20  List<GameObject> _spawned_objects = null;
21 
25  public override string PrototypingTypeName { get { return "ObjectSpawnerConfigurable"; } }
26 
27  protected override void PreSetup() {
28  this.DestroyObjects();
29  this._spawned_objects = new List<GameObject>();
30  this.SpawnObjects();
31  }
32 
33  void DestroyObjects() {
34  if (this._spawned_objects != null) {
35  foreach (var o in this._spawned_objects) {
36  Destroy(o);
37  }
38  }
39 
40  foreach (Transform c in this.transform) {
41  Destroy(c.gameObject);
42  }
43  }
44 
45  void SpawnObjects() {
46  if (this._object_to_spawn) {
47  var dir = Vector3.up;
48  if (this._axis == Axis.X_) {
49  dir = Vector3.right;
50  } else if (this._axis == Axis.Z_) {
51  dir = Vector3.forward;
52  }
53 
54  var transform1 = this.transform;
55  for (var i = 0; i < this._amount; i++) {
56  this._spawned_objects.Add(Instantiate(this._object_to_spawn,
57  transform1.position + dir * i,
58  Random.rotation,
59  transform1));
60  }
61  }
62  }
63 
64  void OnApplicationQuit() { this.DestroyObjects(); }
65 
66  public override ISpace ConfigurableValueSpace { get; }
67 
68  public override void ApplyConfiguration(IConfigurableConfiguration obj) {
69  if (this._spawned_objects.Count < obj.ConfigurableValue) {
70  var go = Instantiate(this._object_to_spawn, this.transform);
71  this._spawned_objects.Add(go);
72  } else if (this._spawned_objects.Count > obj.ConfigurableValue) {
73  if (this._spawned_objects.Count > 0) {
74  this._spawned_objects.RemoveAt(this._spawned_objects.Count - 1);
75  }
76  }
77  }
78  }
79 }