Search Unity

Script class cannot be added because it is abstract.

Discussion in 'Editor & General Support' started by MosquitoByte, Jun 29, 2020.

  1. MosquitoByte

    MosquitoByte

    Joined:
    Sep 17, 2018
    Posts:
    213
    Hello all, i was following brackeys' tutorial on save systems found here:
    and decided to put it into a scene to give it a test run. However attempting to add my script "SaveSystem" to an object gives me the error saying that i cannot because it is abstract. Code below:
    Code (CSharp):
    1. using System.IO;
    2. using UnityEngine;
    3. using System.Runtime.Serialization.Formatters.Binary;
    4. public static class SaveSystem
    5. {
    6.    public static void SaveGame (SaveData savedata)
    7.     {
    8.         BinaryFormatter formatter = new BinaryFormatter();
    9.         string path = Application.persistentDataPath + "/data.ftyfr";
    10.         FileStream stream = new FileStream(path, FileMode.Create);
    11.  
    12.         SaveData gamedata = savedata;
    13.  
    14.         formatter.Serialize(stream, gamedata);
    15.         stream.Close();
    16.     }
    17. }
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,911
    You can only attach classes which extend from MonoBehaviour to GameObjects. It's also declared as static so it can't be Instantiated in any case. I don't see any Unity callbacks like Start(), or Update() on this class so what's the motivation for attaching it to a GameObject?
     
  3. MosquitoByte

    MosquitoByte

    Joined:
    Sep 17, 2018
    Posts:
    213
    So that it can be used. I thought you always have to put scripts on gameobjects for them to exist in-game?
     
  4. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,911
    Nope, that's a misconception you picked up somewhere. You can use plain old C# objects and classes to your heart's content. Of course in order to interact with most Unity things, and for the game engine to call your code you will need to have some MonoBehaviours attached to some GameObjects.

    Since you have a static method here you can call it from pretty much any context in any of your scripts.
     
  5. SmaugTheDaug

    SmaugTheDaug

    Joined:
    Oct 4, 2022
    Posts:
    1
    Hi, I know this is an old discussion but I am having a similar issue, all my code is the same and when I drag the script into the button it's fine except for the fact that the only options in the dropdown are string(). There is no Save() or Load().
     
  6. halley

    halley

    Joined:
    Aug 26, 2013
    Posts:
    2,445
    That's a completely different issue, worthy of you starting a completely different thread. In your own thread, show your class code with the code tags.