Noob question to classes

Hi. I’ve a question about using classes.

I never learned programming and the tutorials helped me a lot; but finding the best solution is still a quest at its own.
For an inventory system, where you drag an item into a canvcas inventory window, the item object will be disabled and an item canvas will be created representing the item in the inventory, I need a script that handles both the drag of the item object and the actions taken to creat the canvas (that script must be seperated from the inventory window).

To simplify the process, I thought about using a class to do all that stuff I can call from other scripts (like the inventory canvas event raycast system that recognizes the cursor moving into the inventory).

Now, is that the meaning of a class to ‘work’ in the background and be called from any script that needs it without beeing present in the scene at all? That would simplify a lot of things:

  1. InventoryScript as class somewhere in the project folder, not in the scene, connecting actions from inventory canvas and cursor actions.

  2. CursorActionScript, handling a ScreenpointToRay raycast to select item objects in the game world.

  3. InventoryCanvasScript, present as component at the inventory canvas recognizing cursor event (OnPointerEnter) to call different actions by the InventoryScriptClass.

  4. => no need to get reference to a ‘master-inventory-handler-script’ somewhere in the scene that must be called from both scripts to work together.

Or is there even a better solution?

Scripts can work in the background without being in your scene at all. However, you will have to learn some key ideas such as constructors in classes. For example, if you wanted to access your CursorActionScript and use its functions, without having it being assigned to an object in your scene, you can do that like this:

    public class CursorAction
    {
        public bool IsSelected;

        // When a new initialisation of a class is made,
        // the constructor is the first thing that is run
        // Think of constructors as the start() method of any class
        public CursorAction() // This is a constructor
        {
            // handle raycast
            // set IsSelected to true, if raycast hit object
            //....
        }
    }

This class can then be called anywhere in your scene in any script by writing:

    CursorScript cursorScript = new CursorScript();

    if (cursorScript.IsSelected)
    {
        //...
    }

However, this creates a fresh, new instance of that class meaning, any data in other instances are not saved. Therefore you cant do this with an inventory system, so it has to be attached to an object in your scene.

You can access those scripts as well, without creating new instances, by using GetComponent<>()
as well, which is better.

I hope i answered your query… @Ambrose998800