- Home /
Add a reference to non-monobehaviour class to a gameobject
I have many objects deriving from a non-monobehaviour class. I have a temporary gameobject, and i want it to have a reference to one of those objects.
Is there any other way to do it beside creating a new script attached to it being a monobehaviour class with just that one reference?
Answer by FlaSh-G · May 22, 2018 at 09:52 AM
You can make a MonoBehaviour component that references multiple of your objects instead of one at a time.
Either way, GameObjects are containers for components and otherwise offer no way of adding additional semantics.
Answer by Tobychappell · May 22, 2018 at 11:02 AM
If there is some other overarching manager type class that is creating this temporary GameObject that also knows the reference to add to this gameobject you could hold a public static Dictionary and add them to the dictionary when they are created.
In your custom object you could use the deconstructor to tell the manager class to remove the GameObject from the dictionary.
So if you need to find the reference of your custom object associated to a certain GameObject you can query the manager class.
Answer by Harinezumi · May 22, 2018 at 11:36 AM
You could try using ScriptableObject
as an intermediary for the reference, and assign an instance of the ScriptableObject
(a scriptable object asset) to your the script on your empty game object. That is, you could create a class that derives from ScripableObject
(maybe named BaseClassHolder
?), and that has the reference to an object you want (maybe it even instantiates it). Then expose the reference through a public method.
But if you provide more information about what you want to achieve, maybe we can find a more specific solution.