I am trying to enable/ disable a script on a UnityEngine GameObject dynamically based on a string of the class name.
I am looping through a list of strings (the class names) and trying to get the script component on the gameObject using gameObject.GetComponent().
My method:
private void changeWeaponScript(int weaponIndex) {
if (weaponInventory.ElementAtOrDefault(weaponIndex) != null) {
for (int i = 0; i < weaponInventory.Count; i++) {
if (weaponInventory[i] != weaponInventory[weaponIndex]) {
if (weaponInventory[i] != null) {
Debug.Log("disable " + weaponInventory[i]);
(GetComponent(weaponInventory[weaponIndex]) as MonoBehaviour).enabled = false;
}
}
}
Debug.Log("enable " + weaponInventory[weaponIndex]);
(GetComponent(weaponInventory[weaponIndex]) as MonoBehaviour).enabled = true;
}
}
I have also tried getting the type using Type.GetType:
Type weaponClass = Type.GetType(weaponInventory[i]);
gameObject.GetComponent(weaponClass).enabled = false;
Any suggestions would be appreciated.