1
\$\begingroup\$

What I'm using for the scriptableobjects that requires a reference of a gameobject in scene is for scheduling events like for moving. Meaning a scriptableobjects should have a gameobject or waypoint for an npc to go to.

Is there a workaround to scriptableobject to have reference of a gameobject in scene? Or are there any better ways to do this?

\$\endgroup\$
  • 1
    \$\begingroup\$ AFAIK, it's not possible. Scriptable objects are assets (see the SO the same way as materials), so they can reference other assets only. The only "work arond", is to have a MonoBehaviour referencing the SO and the gameobject in your scene, and make the MonoBehaviour "inject" the gameobject into the SO. \$\endgroup\$ – Hellium Oct 2 '17 at 16:17
  • \$\begingroup\$ Thanks. Maybe I'll do that if there are no more other replies. \$\endgroup\$ – javurtez Oct 3 '17 at 0:22
2
\$\begingroup\$

Sorry, but that's not going to work. ScriptableObjects are supposed to act as assets which can be reused between scenes. That means you can't and shouldn't make them dependent on objects which exist in only one scene.

But what you can do instead is:

  • Ugly workaround 1: Have the ScriptableObject find its object(s) at runtime. You can do that by tag, by name or by their position in the hierarchy. Just keep in mind that most methods to find objects are slow, so you should do this once in OnEnable() and not whenever that object is requested.

    The major drawback of this solution is that you won't be able to just drag&drop game objects to the fields of the scriptable object. You would have to enter some description and then you will have to start the game to see if that description finds the correct object.

  • Ugly workaround 2: Make the ScriptableObject's responsible for instantiating the objects they need. Note that it is possible to reference prefabs from a ScriptableObject.

    This will of course be difficult to do when the ScriptableObjects are supposed to share objects between each other.

  • Alternative solution which might actually work: Turn your ScriptableObject class into a MonoBehaviour class. Instead of creating a bunch of assets, create a bunch of invisible game objects which live in your scene hierarchy and pretend to be assets. You can then assign other objects in the scene to the properties of these objects and then assign the objects to properties of other objects.

    One advantage of this solution is that it allows you to add some scripting to your objects which gets executed in edit mode. For example, when the object represents a route consisting of multiple waypoints, then they could visualize that route in the scene editor by drawing a series of lines.

I'm looking forward to playing your game.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.