- Home /
GetComponent via String name?
Hi, I'm trying to GetComponent with a String name. Is there a way to convert a string to a Type identifier?
Answer by Drigomen · Mar 15, 2017 at 09:19 AM
I'm trying to GetComponent with a String name
Easy, you can use: GetComponent(string type)
. From the oficial docs: https://docs.unity3d.com/ScriptReference/GameObject.GetComponent.html
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...
Answer by smoggach · Jan 30, 2015 at 09:46 PM
This depends more on the language you're using.
C#: https://msdn.microsoft.com/en-us/library/aa310400%28v=vs.71%29.aspx
In java you would use the method Class.forName().
Answer by Rispat-Momit · Mar 14, 2017 at 11:28 PM
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[i]) as MonoBehaviour).enabled = true;
}
}
Your answer
Follow this Question
Related Questions
GetComponent and converting string to Type type 1 Answer
Passing a Script Name to a Function 2 Answers
Can i give GetComponent a variabel instead of a scriptname? 1 Answer
What's the difference between GetComponent and GetComponent(StringName)? 1 Answer
How Can I Change GetType() And GetField() And GetValue() ? 2 Answers