Is it possible to have multiple scripts that you can reference with one type? Like how you can make a reference for BoxCollider
, SphereCollider
, and other collider types with Collider
.
So if I have, for example, 2 scripts; LandUnit
and AirUnit
, they both have a public speed
variable. Is there a way to create a variable that accepts either of those scripts, and access values that exist in them?
Something like;
public Unit unit;
Debug.Log(unit.speed);
yes, look into abstract classes and inheritance.
you can do:
public abstract class base
{
public speed;
public base(){}
}
public class A: base
{
public A() : base()
}
public class B: base
{
public B(): base()
}
and now you can use both child classes with the base constructor:
base object1 = new A();
base object2 = new B();
In addition to @sisse008 's answer, you can also create an interface and have both classes implement the methods. Then instances of both objects can be placed into a container that holds the interface type.
Just know that on referencing objects in that container as the interface type you will only be able to call methods available to the interface and not the other two types. This is true for both base classes and interfaces.