- Home /
How to add items (or players) to the scene from classes?
Ok, I am a bit confused, and what I have read until now does not help a lot (but maybe I'm not asking right). I am learning Unity by creating a dungeon crawling RPG. It uses classes (and extensions) for mobs, players, items, everything. Now we have some of the following classes:
Item:MonoBehaviour -> Equipable :Item -> Weapon:Equipable
Similarly we have Character:MonoBehaviour -> Player:Character, Npc:Character
Now I got these classes all filled in with variables and everything. The Player class adds a n input movement controller while the Npc one adds AI, Items have sprites etc. I am even using generic empty prefabs for players and items to simplify some parts.
Now my problem is, when it's time to add all that stuff to the game (as game objects), what's the best way to do it? I cannot obviously do it in the constructor, because it returns an object from that class, not a game object. Do I add a "spawn" function for players for instance, which does that? When a player drops an item from an inventory, do I do the same for that?
I don't want a lot of objects in my game scene, so I like to keep stuff in arrays and use physical (game object) representations when I must. Can anyone guide me here?
Edit: To make this clearer:
A class is a blueprint for an object and the constructor is how the object is built. I want to use this logic for game objects. Can / should I?
Answer by 767_2 · Sep 22, 2014 at 05:10 PM
why dont you use Instantiate to make gameObject out of prefabs and if you want it more robust you should use object Pooling here is tutorial
Because I'm not only trying to learn Unity, but I'm also trying to improve my OOP skills. And I like the create from code approach, my prefab should be my class. Prefabs are there to make our lives easier, but I want to learn it the "proper" way.
you mean you want to create an object without instantiating it
this.createObject(gameObject, Vector3, Quaternion);
void createObject(obj, pos, rot) {
Instantiate(obj, pos, rot);
}
Probably totally different from what you want, but if you want a custom call for the "Instantiate", do something like this.
Your answer
![](https://koobas.hobune.stream/wayback/20220613163546im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to access an instance of a class when the class isn't known 2 Answers
Add an instance of a script as a component? 1 Answer
Why does my class script not recognize variables in its own instance? 1 Answer
Fade 2 out of 3 gameobjects on the screen who have the same material 2 Answers
What is an instance of a GameObject? 1 Answer