- Home /
Extending MonoBehaviour to share code between Objects
I am thinking in a traditional OOP way and maybe that is messing me up here, I have a game manager which has a reference to a selected object and pulls data from that object, I.E Name, array of ui options, currentLevel, goldAmount, etc
Now I have 10 buildings I use, that all have these options, and onClick my game manager uses these properties. Now If click a gameObject without these properties, it could cause problems If I don't have the correct properties on them. So is the best way to handle this using derrived classses, or to add a component to each building I.E
OOP Monobehavior->SelectableObject-> SomeBuilding (I am not sure how to accomplish this in unity)
or just add a component to the gameObject called SelectableObject that has required properties. (not 100% sure how to do this either)
Any tips or examples would be awesome! Thanks!
Sammy
Answer by Lao2211 · Oct 04, 2016 at 05:14 AM
Last time I checked the only way to create custom components is to derive from MonoBehaviour so you are going the right way there.
SelectableObject implies that the object is selectable. Then I propose to not allow any selection at all on game objects that doesn't have that script attached.
You can check if an object has the component with something like this:
SelectableObject.cs
using UnityEngine;
using System.Collections;
public class SelectableObject: MonoBehaviour
{
public int Health = 0;
public static bool IsSelectable (GameObject object) {
SelectableObject component = object.GetComponent<SelectableObject>();
if (component != null)
return true;
return false;
}
The other option is to just let the game fail as loud as it wishes. Let it try to access innexistent properties and do bad type casts. So you know that a scene is invalid during your tests, the end user won't see the errors because you will correct all of them prior to release.
But I think that is not very flexible, as I doubt you want an scene of all selectable objects. You probably are using some form of raycast to hit the selectable objects, but in an scene with only some objects being selectable, the rays will hit non selectable objects sometimes, we don't want a crash only for that, so check if an object has the SelectableObject component and simply do nothing if it doesn't sounds better.