Hi all,
iam pretty new to unity, and i wondered how to use the ScriptableObject to create a class that can be instantiated.
i now that i cant use a constructor, but how do i add the variables to the instance ?
in c# i would have probably something like this for the constructor:
public GameClass () {
this.gamevar1 = gamevar;
this.gamevar2 = gamevar2;
}
so how can i put some equivalent code in my: GameClass:ScriptableObject so that every instance gets the variables it needs ?
cheerz
You have to either make some other method called “Initialize” or something similar, which takes as arguments the parameters you would’ve normally passed to a constructor. Part of the reason we can’t create constructors for scripts is that Monobehaviors all have native counterparts inside the unmanaged part of the Unity engine. This is also why you have to call Destroy to get rid of them, and can’t rely solely on the managed garbage collector to clean up memory. If you instantiate scripts with its constructor instead of through Instantiate on the object it’s attached to, you’ll end up with only the C# / .Net / Managed part of the script, it won’t be created in the engine.
So, to mimic what you’ll normally do with a constructor, like I said, make an initialize method you call immediately after instantiation, like so:
Transform yourObject = (Transform)Instantiate(yourPrefab, Vector3.zero, Quaternion.identity);
YourScript attachedScript = yourObject.GetComponent<YourScript>();
attachedScript.Initialize(int value1, float value2, string value3); // Sets values in the script instance like you would've done in the constructor