Assigning Scriptable Objects in script

Hi, bit of a noob at Unity so sorry. Currently at runtime I’m adding an empty game object then assigning a script to it with no issues but I can’t work out how to add in the scriptable objects this way since AddComponent doesn’t work for assets.

I have two sets of different Scriptable objects all containing different information to build the object off of, one being noise data and the other shader data. The end result is to essentially mix and match these two assets and create different results.

Hi @PsuedoKirito

You could put your ScriptableObject class Asset file into Resources folder, and then load it from there (if you can’t just assign it from the inspector):

[SerializeField] ScriptableObject scriptableObject;

private void Start()
{
     scriptableObject = Resources.Load<SomeScriptableObject>("AssetName");
}
4 Likes

@eses
Hi, sorry for the late reply. I’ve loaded the asset, but I can’t apply the asset in the script. There are no errors but the asset isn’t being loaded in the script I’ve applied to the generated gameobject.

@PsuedoKirito

Maybe show your code, so folks can help you.

The ShapeSettings is just a class to hold variables that you can change from the inspector and create the scriptableobject with.

    void Start()
    {
        GameObject genplanet= new GameObject();
        genplanet.AddComponent<Planet>();
        obj = Resources.Load<ShapeSettings>("Shapes/Destroyed");
    }

Then all the settings are handled in a different file.

I just don’t understand how to add obj to Planet as a ShapeSettings asset.

@PsuedoKirito

If your Planet class has a property or public field (add one if you don’t have):

public ShapeSettings obj;

And then in your other script, get the component to access your obj field:

var planet  = genplanet.GetComponent<Planet>();
planet.obj = Resources.Load<ShapeSettings>("Shapes/Destroyed");

This will only work runtime.

2 Likes

That did it, thank you