I have a GargoylePrefab
in Unity that is assigned to a list of objects in my component Units
. The prefab has a Gargoyle
script attached to it (which inherits from the abstract Enemy
).
.
I am having trouble setting the inherited property EnemyType Type
in my GargoylePrefab
object according to the script. When I try accessing the script component of the prefab and logging its Type
property, I get an unexpected/unwanted result ( Invalid
instead of Gargoyle
).
.
Am I setting the value in the wrong place? I have also tried setting it in Gargoyle.Awake()
but the result is the same. How do I fix this problem?
.
See below for implementation overview:
// EnemyType.cs
public enum EnemyType { Invalid, Gargoyle }
// Enemy.cs
public abstract class Enemy : MonoBehaviour {
// Because EnemyType's first definition is "Invalid"
// Subclasses of Enemy have to set their type to something else
// to avoid having an unwanted or undefined type
public EnemyType Type { get; protected set }
...
}
// Gargoyle.cs
public class Gargoyle : Enemy {
private void Start() {
Type = EnemyType.Gargoyle;
}
}
// Units.cs
public class Units : MonoBehaviour {
public GameObject[] EnemyPrefabs;
public void OutputPrefabTypes() {
// This is just a method for testing.
// I -know- only one GameObject (GargoylePrefab) is in the array.
foreach (GameObject prefab in EnemyPrefabs) {
Enemy genericRef = prefab.GetComponent<Enemy>();
Gargoyle gargoyleRef = prefab.GetComponent<Gargoyle>();
Debug.Log(genericRef.Type); // Expected: Gargoyle, Actual: Invalid
Debug.Log(gargoyleRef.Type); // Expected: Gargoyle, Actual: Invalid
}
}
}