Quantcast
Channel: Questions in topic: "class instance"
Viewing all articles
Browse latest Browse all 131

How to correctly use MonoBehaviour inherited class?

$
0
0
Hi, I'm trying to use a class structure to store coroutines responsible for spawning enemy waves. I already regret the idea but want to get to the bottom of it. My **Spawn_Manger** script is attached to an empty object and I call my major coroutine **Timeline()** from **Start()** public class Spawn_Manager : MonoBehaviour { //vars Start(){ //checks if (_player.GetComponent().Alive()) { StartCoroutine(Timeline()); } } In **Timeline()** I call wave-spawning coroutines one by one yield return StartCoroutine(wave1(t_start_0,,,,)); I got those coroutines running directly, but wanted to store them in a meaningful way, so I created a class inside **Spawn_Manager**. Here it is with only the simplest function. class Wave_creator : Spawn_Manager { public IEnumerator Pos_range(float t_wave_end, float t_start_pause, float dt_enemy, Wave_dir dir) { yield return new WaitForSeconds(t_start_pause); while (Time.time <= t_wave_end) { Enemy_create(dir); if (Time.time + dt_enemy > t_wave_end) { yield return new WaitForSeconds(t_wave_end - Time.time); } else { yield return new WaitForSeconds(dt_enemy); } } } } That class uses **Enemy_create()** and other methods from **Spawn_Manager**, so I want to inherit. Now, I know that **MonoBehaviour** inherited classes cannot use **new** to create an instance, but I do not understand how to correctly do it with **AddComponent**. When I use it in **Start()**, Unity rejects the script but no error is displayed in the Visual Studio. Wave_creator wave = gameObject.AddComponent(); I then pass **wave** down to **Timeline()**. I've tried different syntaxes and googled for things I do not fully understand, like singletons. Nothing helped so far. The main idea was to use sub-classes to divide various spawning coroutines by types, so that i could use something like this in **Timeline()**. yield return StartCoroutine(wave.simple.right(t_start_0,,,,)); where **wave** is an instance of **Wave_creator**. ***I would like to know, how exactly you create an instance of the class in such case? And just in general, is there a much better way to store functions with similar functionality results?*** I've started to get into Unity just recently and am trying to do simple things in a complex way, so it is more of "Can it work this way?" question. **Thank you a lot!**

Viewing all articles
Browse latest Browse all 131

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>