- Home /
How do you get the results from an enum in a different script
I'd like to use the results from an enum.
I am attempting to check the result of an enum from a different script. I thought I could do this by storing the result of the enum into a string and use an "if" statement to compare the value. However, I keep getting "object reference not set to an instance of an object." Any help with this is appreciated. Also the result doesn't have to be a string. I just used one because I was hopeful that it would work.
In one script I have...
.
public enum ShipList
{
Frigate,
Fighter,
Cruiser,
Destroyer,
BattleCruiser,
Dreadnaught
}
public ShipList selectedShip;
public string shipType;
void Update()
{
shipType = "" + selectedShip;
}
public ShipList selectedShip;
.
In my 2nd script I have...
public GameObject ship;
private BetterShipGenerator shipGenScript;
void Start ()
{
shipGenScript = ship.GetComponent<BetterShipGenerator>();
}
void Update ()
{
if(shipGenScript.shipType == "Frigate")
{
Debug.Log("I know a Frigate when I see one!");
}
}
if(shipGenScript.shipType == "Frigate")
could be
if(shipGenScript.shipType == whateveryousavedScript1as.ShipList.Frigate)
EDIT: it's probably saved as BetterShipGenerator
for safety, you might also want to check whether shipGenScript
is null or not... just in case it didn't find the component.
Answer by unity-huunity · Jan 26, 2015 at 01:32 PM
You can declare enums outside your class. If you write public in the front of it you will be able to use your enum from entire solution.
Your firs cs. file
public enum ShipList
{
Frigate,
Fighter,
Cruiser,
Destroyer,
BattleCruiser,
Dreadnaught
}
public class YourAwesomeClassNumberOne: MonoBehaviour {
public ShipList sl = ShipList.Frigate;
}
Your second cs. file can be like:
public class YourAwesomeClassNumberTwo: MonoBehaviour {
public GameObject ship;
void Start(){
if(ship.GetComponent<BetterShipGenerator>().sl == ShipList.Cruiser){
Debug.Log("Weeee");
}
}
}
Your answer
Follow this Question
Related Questions
Instantiating a Coroutine? 2 Answers
Value will not return from ArrayList, C# 1 Answer
Avoid NullReferenceException with Singleton 3 Answers
Having trouble with static references. 1 Answer
How would you convert string to enum 1 Answer