- Home /
Creating new scriptable objects at runtime
Hey guys, so I am working on a fighting game where you manage a team. I would like the player to be able to pick there team members from a list of randomly generated fighters.
So far, I have some scriptable objects that hold different stats (eg name, health, strength) that are assigned to the fighters. However, these need to be set in the editor. I would love to know if there is a way to create new scriptable objects at run time, and generate their stats randomly. This scriptable object would then need to be saved to be accessed between scenes or when the game is later opened.
It should be possible for an infinite amount of characters to be created.
Any help would be greatly appreciated, or an alternative to using scriptable objects would be great !
For clarification, a similar system would be in pokemon. You stumble upon randomly generated pokemon, each one belonging to a specific "race" but that individual having its own distinct and random stats. Once caught, it is saved.
Answer by Hellium · Jan 27, 2019 at 10:23 AM
You can create Scriptable Objects at runtime by calling CreateInstance
But, keep in mind that these scriptable objects won't be saved automatically in your project (not even on the disk) like the ones you use in the editor. You will have to save and load them by yourself. To do so, you can use a custom serializer or the JsonUtility
of Unity + System.IO.File.WriteAllText
Hey, thanks for your answer ! Im not familiar with the create instance function, do you think you could elaborate a little bit more or provide a very quick/simple example ? I would really appreciate it.
As for the saving/loading, thanks for referring me to some solutions I have found some documentation about them and I think I can look into those a bit more myself.
var obj = (YourClass)ScriptableObject.CreateInstance(typeof(YourClass));
Note that we have a generic version of the CreateInstance method for a long time already. So you usually do
var obj = ScriptableObject.CreateInstance<YourClass>();
or if you like to specify the variable types explicitly:
YourClass obj = ScriptableObject.CreateInstance<YourClass>();
Finally note that ScriptableObject is a UnityEngine.Object derived type. So you can simply use Instantiate to create a clone of an existing one. So the clone will be a completely independent / new object but with the same values as the source from which it was cloned:
YourClass newObj = Instantiate(obj);
Your answer
Follow this Question
Related Questions
How do I make a photography function? 0 Answers
Selecting an ability based on UI image/button, and thereafter selecting a target for the ability 0 Answers
Handling change in Class variables with saving ScriptableObject 2 Answers
looking for a way to set an integer to another number based on a condition. 2 Answers
How to Instantiate a GameObject from a ScriptableObject piece of script? 0 Answers