This is my issue:
I want to assign a script that inherits from an abstract class to a GameObject.
I used to create MonoBehaviour scripts like “BirdScript” or “CarScript” but I want use proper classes and be able to control the gameobject the class is attached to.
Let me show you an example:
I have to following classes
public abstract class Shape : MonoBehaviour {
private int weight;
private string color;
protected int Weight
{
get { return weight; }
set { weight = value; }
}
protected string Color
{
get { return color; }
set { color = value; }
}
//Example abstract method
public abstract void calculateVolume();
}
public class Cube : Shape {
public void Move()
{
Vector3 pos = transform.position;
pos.x = 2;
transform.position = pos;
}
public override void calculateVolume()
{
//Just print a string
MonoBehaviour.print("Cube volume");
}
}
I also have a prefab GameObject called MyCube which has the Cube class attached
Now I want to create an instance of MyCube from another GameObject which has the following script attached
public class ShapeManager : MonoBehaviour
{
[SerializeField]
public GameObject cube;
// Use this for initialization
void Start()
{
GameObject c = Instantiate(cube);
c.GetComponent<Cube>().calculateVolume();
c.GetComponent<Cube>().Move();
}
// Update is called once per frame
void Update() {}
}
The GameObject cube has the MyCube prefab attached using the Inspector.
My questions are:
What if Cube wouldn’t inherit a Monobehavior class ?
Is this approach correct ?
Does it violate OOP ?
The way ShapeManager controls the cube is right ?
GameObject c = Instantiate(cube);
c.GetComponent<Cube>().calculateVolume();
c.GetComponent<Cube>().Move();
My apologies for this long post