Monday, July 12, 2010

Enums in Unity3d

So, I've seen a lot of hacks getting enums to work properly in Unity. The problem comes when you are trying to pass enums back and forth between scripts. Some say enums are global while others claim you have to reference the script first (somescript.enumName). I've found some of the hacks helpful, but I recently ran into an issue that none of them seemed to fix.

What if you have two instances of the same script that are each trying to reference each other's enums. Here's an example

projectile.js :
enum projectileType = {laser, missle, mine}
var theType : projectileType.laser;

onCollisionEnter(other : Collision) {
if (other.gameObject.GetComponent(projectile).theType == projectileType.laser) {
//do something
}
}


This never seems to work for me, and many of the hacks fail when I add '#pragma strict' to the code. For some reason, the compiler thinks that other.gameObject.GetComponent(projectile).projectileType is of type System.object, and therefor cannot be compared to projectileType. If you are having this problem to, try this:

onCollisionEnter(other : Collision) {
if (other.gameObject.GetComponent(projectile).theType.ToString() == "laser") {
//do something
}
}


Obviously not ideal, but it worked for me. Let me know if it works for you.

1 comment:

  1. I know it's old, but let's leave the answer here:

    enum ProjectileType {laser, missle, mine}
    var theType : ProjectileType = projectileType.laser;

    ReplyDelete