- Home /
Classes and subclasses typecasting in unityscript
Hi !
Code first, so i don't get lost into useless specifications:
class mydevice
{
var integrity:float=100;
var deviceName:String;
}
class battery extends mydevice
{
var storage_power:float
}
class generator extends mydevice
{
var recharge_rate:float=25;
}
Now, since my goal is to add mixed types of device subclasses (batteries and generators) into a list, in order to compute, for example, the sum of storage_power or recharge_rate
And I succeded doing that, creating a list of type "mydevice". But this way, i can only see in the inspector, the variables belonging to the "mydevice" class, but not the subclass variables (and that definitively makes sense).
My unelegant solution was to put an enum "tagging" the mydevice, and checking for it's original subclass
for(var i=0;i<ship_devices.Count;i++)
{
if ((ship_devices[i].type == ShipDeviceType.Battery))
{
var typecast = ship_devices[i] as battery;
print("this is a battery, with storage = "+typecast.storage);
}
}
I'd like to know if there is a better method than this, which by the way surprisingly works in retrieving the subclass variables. Basically what i'm looking for, is being able to add different derived subclasses to a single list, without "flatting" them to the class they extend, without having to tag them or put enums just to mark a difference between them.
Thank you and have a good day !
Please indent code. Please leave proper spacing when writing code. Please use UpperCamelCase
for class names. Please don't double up ()
's.
To check the type you can use the is
keyword.
if (device is Battery) {
Looks like keyword "is" doesn't belong to Unityscript, you may haven't noticed i'm using it because of bad indentation or such
In that case (Found this looking up the same problem for C#)
if (device.GetType() == typeof(Battery)) {
But I still can't find where your using the is
keyword...
if (device.GetType() == typeof(Battery))
is not the same as if (device is Battery)
- But if (typeof(Battery).IsAssignbleFrom(device.GetType())
is.
Your answer
Follow this Question
Related Questions
Classes and subclasses typecasting in unityscript 3 Answers
How to add the score in a quiz game with text input field and a button. 0 Answers
Wave manager that enables multiple gameobjects after X seconds? 0 Answers
Handling different combinations of enum selection 1 Answer
How to perform Explicit typecasting in UnityScript? 2 Answers