Hello dear community!
I am asking you guys for help today because, well i am running into problems with unity and C#(Well mostly just Unity).
The problems i am having mostly have to do with the fact that when creating(Instantiating) Game objects, i feel like i loose a certain amount of control, that i feel i normally have using constructors. An example could be “spawning” a enemy, and add him to a list of type Enemy. In the case of Unity it seems “dangerous” that i have to Instantiate a Prefab, hope it has a script of type Enemy (With abstract classes, this fear of mine is even worse) and add that script to the List? Normally you would just create a new Instance, and be done with it.
Like in the following example(Overly simplified ofc)
List<Enemy> enemies;
Enemy newEnemy = new Enemy(params);
enemies.Add(newEnemy);
Where in Unity it seems like the “way” of doing it would be:
List<Enemy> enemies;
GameObject newEnemy = (GameObject)Instantiate(enemyPrefab, position, rotation);
Enemy enemyScript = newEnemy.getComponent<Enemy>();
enemies.Add(enemyScript);
This, seems, not only clumsy but reminds me of the old AS2 days of attachMovieClip(And for those of you who remember, or has to work with scaleform, can maybe understand why sweat is starting to form on my head)
I have tried my “own” way of “solving” the issue, using init() methods, or pseudo constructors, i tried classes that upon creation(the class not the GameObject) instantiate the prefab on its own. Or Prefabs, that register themselves to other classes, upon creation. But it just does not feel right.
So i keep thinking that there must be a way around this. A better way of working with GameObjects and MonoBehaviors. And i hope you guys might have some tips
That was a great answer, and pretty much nailed what i wanted to know. thanks a bunch! I guess in the end, i was the one trying to force a more "deep" class structure hehe. But yes creating helper classes for instantiating of prefabs seems very nice, and I completely forgot about AddComponent too, which could work nice in a lot of circumstances. But so many solid, and fast replies so fast, that made my Monday morning the best in a while!
– runeraskWe love good questions :D
– whydoidoit