- Home /
String to enum
Can I make my string into a enum in javascript>
it would make this switch function unnessesary and I won;t have to edit it when i possibly add an element to an enum.
@RPC
function SetStation(setToo :String) :void
{
switch(setToo)
{
case("Jump"):
currentUpgrade = Upgrades.Jump;
break;
}
}
Upgrades is my enum and I wonder if I could have something like Upgrades. + the jump string = Upgrades.Jump
Answer by Paulius-Liekis · Jan 21, 2013 at 03:08 PM
Google says this:
var value : Upgrades = (Upgrades) Enum.Parse(typeof(Upgrades), setToo );
The (upgrades) gave me a compiling error but this seems to work (Declared currentUpgrade earlyer)
currentUpgrade = Enum.Parse(typeof(Upgrades), setToo );
Yes, UnityScript doesn't have the "c-style" cast. UnityScript will cast it implicitly.
Does this look different in C# because it tells me it doesn't´t now Enum. It doesn't´t work with enum as well. I´m using System.Collections.
the Enum class doesn't exist in System.Collections, it exists in System(https://msdn.microsoft.com/en-us/library/system.enum.parse(v=vs.110).aspx), put a using statement to include System
using System;
or qualify the name space
System.Enum.Parse(etc.....
Answer by Owen-Reynolds · Jan 21, 2013 at 04:36 PM
The traditional method is to treat enums as ints, when needed. Say the enum is {"walk", "run", "jump"}. That's just a fancy way so we don't have to write if(up==0)
and have to remember that upgrade #0 is walk. But when you write up=Upgrade.walk
to computer really stores it as up=0
.
So you'd send the RPC: int upNum = (int)setToo
, which would send a 2 for "jump". Then translate back using Upgrade up=(Upgrades)upNum
.
The funny thing is, the number will have been a 2 the entire time. All the castes are doing is telling the computer that it's OK to use the "real" 0,1,2 code numbers.
But an RPC is already so slow and uses a minimum 4K(?) anyway, that sending "the long way" as a string isn't going to matter unless you send hundreds each frame.
The string is com$$anonymous$$g from a string Array (not every upgrade will be availeble in every level) and I also need the string value again for something else later in the function too. I am using the int values to send enum values in rpc calls and your right I supose it could be a int in this case as well :)
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
String.Split problem 1 Answer
C# Incrementing a String Array 1 Answer
String Assets? 1 Answer
How to use Enum? 1 Answer