- Home /
How to check if variable exists?
Howdy. I've got a base Weapon class with two inheritors: SmallGun and LargeGun. The SmallGun fires in bursts and has a new variable called burstCount. The LargeGun doesn't.
In my scripts, how can I check if the variable burstCount exists in the current Weapon? Failing that, how would I check is the weapon is either a SmallGun or a LargeGun?
Thanks for the time.
EDIT: convert to comment, OP wants JS.
C# objects have a GetType() method. Use it with typeof().
weapon = new LargeGun();
if(weapon.GetType() == typeof(SmallGun)){
weapon.burstCount++; //bad practice. Should have a weapon.IncreaseBurstCount() method or smth
}//else do nothing
I appreciate the answer. $$anonymous$$ost of my code is in JS, tho, so I'll check around if there's an equivalent to GetType and typeof.
You can specify either c# or js tags when posting questions :)
http://rockonflash.wordpress.com/2009/05/22/getting-object-type-in-unity3djavascript/
One quick google later...
Answer by Zoodinger · Oct 28, 2014 at 04:37 AM
Look into Reflection. I don't know how much it is supported by JS, but it does whatever you are asking for. Keep in mind, however, that it's slow. Also, I would still advice that you find a better solution. Having to check if a variable exists is rarely ever a good idea.
I see. So is there a way to check which child class it is then? Something like what Em3rgency posted but for JS?
if weapon is SmallGun {
getBurst
}
seriously? have you searched at all? check my comment above, or just click here: http://rockonflash.wordpress.com/2009/05/22/getting-object-type-in-unity3djavascript/
yeeeah... well, I was hoping for something simpler and faster than getType. and yes, I did research on GetType before.
I've been experimenting on the "is" keyword for some time and it seems pretty close to what I need.