I want to create a set of different 'movement' scripts which I can apply to my games units. Each class will have different calculations for moving the unit around the screen, I am attaching these classes to my Unit GameObject. I want to be able to enable and disable the movement class when it has finished movement calculations so that it isn't working away unnecessarily.
The problem here is that in order to call the enable method, my Unit GameObject must have a reference to the Movement class, but since this class can be a one of many, I can't specify which one it will be.
I tried to solve this by giving my movement classes an interface, IMovement, but GetComponent is only referencing the interface itself and not the class, so I am unable to set the enable property.
The only other solution I can think of is to use class inheritance, but having each method marked as an override is a pretty messy solution.
Anyone have any ideas?
If you are working in C#, you can require property setters and getters through the interface. With this, you could do this:
public interface IEnableable {
bool Enabled { get; set;}
}
and for the implementation
public class aMovement : MonoBehaviour, IEnableable
{
public bool Enabled {
get {return enabled;}
set {enabled = value;}
}
}
you could also do this with a abstract class.
Just cast it:
Component movement = (Component) GetComponent<IMovement>();
movment.enabled = true;
It's a bit unpleasant because there's now the implicit requirement that all IMovement implementors be Component-derived, and no enforcement of that, but it sounds like you were considering that as an alternative solution anyway.
Hi,
Well, my suggestion would be that you should take advantage of the component-oriented architecture Unity provides... In other words, I would put each of your classes in a different script, in this way you coudl use easily GetComponent(aMovementScript).
But this is just my suggestion.
Hope this can help you