Hi, I’m trying to GetComponent with a String name. Is there a way to convert a string to a Type identifier?
I’m trying to GetComponent with a
String name
Easy, you can use: GetComponent(string type)
. From the oficial docs: Unity - Scripting API: GameObject.GetComponent
using UnityEngine;
public class GetComponentExample : MonoBehaviour
{
public const string knownClassName = "Rigidbody";
public string unknownClassName;
void Start( )
{
Rigidbody comp1 = gameObject.GetComponent(knownClassName ) as Rigidbody ;
var comp2 = gameObject.GetComponent(unknownClassName ) as MonoBehaviour;
}
}
Is there a way to convert a string to
a Type identifier?
Yes. As @smoggach said, it depends on the language.
In c#, it sometimes work: System.Type.GetType("yourStringHere")
But, I don’t know why you would want this. If you don’t know the type at compile time, you don’t have other option than cast it as a MonoBehaviour, and you can’t do much with that…
After spending a few hours searching, I found the solution. Here is a small script that I made
This will create an array of Strings where you can write the names of the scripts you want to activate.
var MyScriptNames: String[];
function Start(){
for(var i : int = 0; i < MyScriptNames.Length; i++)
{
(gameObject.GetComponent(MyScriptNames*) as MonoBehaviour).enabled = true;*
- }*
}
This depends more on the language you’re using.
C#: Activator.CreateInstance Method (System) | Microsoft Learn
In java you would use the method Class.forName().