Unity Scriptable Objects issue

2.5k views Asked by At

I have a list in RoomSO that contains premade ButtonSOs that i created in the editor and dragged and dropped into the list. RoomSO is also premade (made in the editor) Then at runtime i create an instance of a ButtonSO and tried adding it to RoomSO buttons. I look at the RoomSO in the editor and i get "Type mismatch". I canĀ“t understand why?

RoomSO script:

 [CreateAssetMenu(fileName = "New Room", menuName = "Rooms/Room")]
 public class RoomSO : ScriptableObject
 {
     public List<ButtonSO> buttons;
 
     public void AddButton()
     {
         ButtonSO bt = (ButtonSO) ScriptableObject.CreateInstance<ButtonSO>() as ButtonSO;
         bt.buttonText = "Hello";
         buttons.Add(bt)
     }
 }

My ButtonSO script:

 [CreateAssetMenu(fileName = "New Button", menuName = "Rooms/Button")]
 public class ButtonSO : ScriptableObject
 {
     public string buttonText;
 }
1

There are 1 answers

1
derHugo On BEST ANSWER

You issue isn't really an "issue".

What happens is that usually Unity expects a ScriptableObject asset reference assigned to the fields in the Inspector. Because the actual use-case of ScriptableObject is to have certain exchangeable data/behaviour container assets.

What you are doing is creating instances on runtime. These instances are only stored in the temporary memory since you never actually store them as assets into your project.

You will see the type mismatch in the Inspector, but actually this means there is a valid reference - otherwise it would say either None (ButtonSO) or Missing (ButtonSO), it only won't be saved once the Playmode ends. The later Missing (ButtonSO) you will see after ending the Play Mode since the List<ButtonSO> will still exist, also the items within it - but the according references you created during runtime will be destroyed.

Your runtime code should still work as expected as long as the Play mode is running.

The same happens btw if you assign e.g. a GameObject field within a ScriptableObject with a reference from the Scene during runtime.


In general though: If you create these instances on runtime - why do they need to be ScriptableObjects? You could just use a normal class.