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.
CodePudding user response:
You can use Reflection to get all the types of subclasses of a given type, and filter those out by a string matching their partial or full name.
In this example I'll get the types of all MonoBehaviour's matching a given string as an IEnumerable. You can then use Unity's functions, such as FindObjectByType, GetComponent, AddComponent, and Destroy to get, create or destroy these components.
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
// ... in some function
string partialClassName = "Sword"; // does not include namespace
string superClassType = typeof(MonoBehaviour); // type of superclass
IEnumerable<Type> types = superClassType
.Assembly.GetTypes().Where(t => t.IsSubclassOf(superClassType) && !t.IsAbstract).Select(t => t.Name == partialClassName));
// types are now a list of subclasses of MonoBehaviour that match "Sword"