Hello, I have created a shop system. In which the players can buy cars, this works completely fine. The cars are added to a scriptable object and are placed in the correct place. Element 0 = player 1.
Element 1 = player 2.
Element 2 = player 3.
Only if you quit the game now it will not save that list. This is because scriptable objects are not stored in build mode, but only in the Unity Editor.
So now I had an idea of how to fix this possibly. Since you cannot save a list of game objects. Namely this;
- save a list of strings. //for example List carNames; //Example in list is BMWCarNumber1
- get a list with every car in the game //BMWCarNumber1 but also MercedesCarNumber2 for example
- see which strings are equal to which game object //For example string BMWCarNumber1 == BMWCarNumber1.name
- Add BMWCarNumber1 to a list of all available cars & see if the car is already in the list.
If so, we will not add it. If not, we will add it. //For Example in List AvailableCars is now BMWCarNumber1
- The player can now choose from any car in AvailableCars
only I have no idea how to compare a string in a list with a gameobject.name from another list of gameobjects
Hopefully someone can help me with this
Sounds like you need your data to be persistent which will involve saving it to disk.
To try this out, serialize the objects you want to save using JsonUtility then store the serialized string it creates with PlayerPrefs. In future you might want to save it to actual save files but while you’re developing PlayerPrefs is great.
Regarding comparing strings to gameobjects, as long as you can guarantee that each gameobject will have a unique name then that will serve fine as its unique identifier. If I were you, I’d write some sort of check in code just to make sure you don’t accidentally have duplicate names. It might be easier to give all cars a unique ID number in case you’d like multiple instances of the same car to be available. Do this by adding a serialized field int to the car script then in OnValidate if it detects this variable to equal whatever value you initialise it to (0 by default) then it will create a new ID and check that ID doesn’t clash with other existing cars.
If in the game you have a collection of all gameobjects when you start, once you have loaded the save data about who owns what car you can update the runtime data such as whether a car is available to buy.
One thing to note when serializing objects is that all custom classes that contain save data need to be serializable. Thankfully, making a class or struct serializable is as easy as adding the [Serializable] tag at the top of it, just above the declaration.
ScripableObjects are great for things like holding a set of all cars available in game but not so much for storing changeable data, as you’ve found out, so I don’t think you car data container needs to inherit from that anymore.
Happy to help with the code if you’d like but see how you get on with this information first