So I did a lot of rewriting of code this week, to make it cleaner and easier to use, especially for anyone new coming into the project. One issue I had was that a lot of the main classes I had in the game (Location, Job, Employee) were all inherited from MonoBehaviour scripts. If you’re unaware, that’s the class you derive from in Unity that essentially allows the script to be attached to a GameObject. If it’s not MonoBehaviour, Unity won’t allow the script to be attached.
Now why is this bad? Well it isn’t inherently bad, but it does cause issues when trying to work with serialization, which allows us to store our data. MonoBehaviour is unable to be serialized, and therefore to save it’s data we have to come up with a system for that. I did do this in fact, but I wanted to cut down on exactly how much it was being used to simplify the project.
So ultimately what I wanted was to be able to have a MonoBehaviour script that can attach to the physical representation of the object, while also having it be easier serializable. So essentially what I did was create a nearly blank MonoBehaviour class called PhysicalLocation, and this had a parameter for a Location class. Now I needed to be able to create this class and fill in the location inside. I didn’t want to have to fill it in manually every time, so I created an extension.
public static Area CreateArea(this GameObject obj)
{
PhysicalLocation pLoc = obj.AddComponent<PhysicalLocation>();
pLoc.type = LocationType.Area;
pLoc.myArea = new Area();
pLoc.myArea.physicalObj = obj;
return pLoc.myArea;
}
This now allowed me to easily create a new area on any GameObject similarly to the GetComponent<>() function. It made it easy for others to use without the potential misunderstanding of needing to manually fill out the information needed for that location.
0 comments on “TC – Working Around MonoBehaviour”Add yours →