Should I inherit from Monobehaviour if the use of my C# script is only to hold script references?
I have a few C# scripts that inherit from monobehaviour. Im doing this so that these scripts can be attached to GameObjects as components but these scripts only serve as holders for references to other gameObjects. should these scripts inherit from monobehaviour or should I do something else?
Answer by FuntikStudio · Oct 30, 2017 at 10:54 AM
Maybe the answer of @KillerOfSteam7 is correct, but I am not still comfortable with concept of statics when it comes to references. What I would do: Have one script that inherits from mono, and attach it to the object. Inside this script, create also public classes with public references. Than inside your class : mono, create instances of these classes and they will appear in the inspector, every class as a changable field.
[System.Serializable]
public class ReferencesOne ()
{
public SomeClass ref1;
}
[System.Serializable]
public class ReferencesTwo ()
{
public SomeClass ref2;
public SomeClass ref3;
}
public class YourClass : MonoBehaviour
{
ReferencesOne rOne = new ReferencesOne ();
ReferencesTwo rTwo = new ReferencesTwo ();
}
I wrote the code outside unity, so be aware of spelling, but the idea I hope is clear. Than in the Inspector you can attach references and you are good to go.
Answer by brunocoimbra · Oct 30, 2017 at 10:37 PM
MonoBehaviours are your only way to directly communicate with the scene at both edit-time and run-time. If you wanted, you could use GameObject.FindXXX to get those references by code, without the need to use one MonoBehaviour for each object, but it would increase you game loading time, and it would become harder to maintain your project as it grows.
@FuntikStudio 's answer is your alternative when you want to re-utilize pieces of code with a great amount of repeated data, another way would be inheritance.
Your answer
Follow this Question
Related Questions
Rotate Player 90 degrees about its Y axis relative to the mouse being dragged between two angles 1 Answer
How to tell if the code flow changed 2 Answers
My Monobehaviour Script doesn't get detected 0 Answers
Why does unity not see monobehaviour? 2 Answers
I seriously cannot learn how to script. What do I do? 4 Answers