Attaching GameObjects to Classes or Attaching Scripts to GameObjects

Hello everyone,

I am new to Unity but a more or less advanced programmer.
I didn’t read any tutorial or howto to get experience with unity, so maybe my question is stupid.

On my current projects (only playing around with unity) I created classes like

public class Player{
   public GameObject geometry;
   public health;

   public Player(){ = 100;
      this.geometry = GameObject.CreatePrimitive(PrimitiveType.Capsule);

in a file called Player.cs. So I have a wrapper class for a GameObject which could contain some more informations like the health attribute.

In an additional file which inherits from MonoBehaviour something like this will happen:

public someClass : MonoBehaviour{
   private Player player;
      this.player = new Player();
      //some more stuff

      //do cool stuff with the player object

I’m doing this because its the way I implemented things with some other technologies like WebGL. But is it the correct way to work with unity? I found out that it’s more common to create a GameObject and attach a script for the behavior of the GameObject.

While using the second mentioned way of using unity it’s f.e. easy to click on a gameObject in the scene and get the attached script as a component. In my case the GameObject doesn’t contain a component script which makes it rather hard to get the additional attributes. In some cases I was able to manage this because I hold all clickable objects in an array (or something similar) which means i could iterate over these arrays and compare (f.e. the position) of all objects with the clicked one.

Is it just a bad idea to create classes like I did? Or is there a way to get the wrapper class of an object in the scene without iterating over arrays?

I would love to hear what experienced Unity programmers will say to my questions.

Thanks in advance!

It comes down to the way the classes are to be used. For example, an inventory, or actor stats, will always be bound to a gameobject, so they can be MonoBehaviors. An item can be a “physical” obejct in the game world (a model of a sword, for example, lying around to pick up), but it can also be added to the backpack so there won’t be a world object, only the item values collected in a clas. In those cases, having a non-MB class for the Item is the better way. The world obejct would then have a MB “Item Holder” script that store an instance of the item class which is accessed when the item is picked up and trasnferred to the inventory.

So in the end, I would decide on a case-to-case basis.