- Home /
Fetching a script name for AddComponent from a text - class doesn't exist?
I'm planning to write a short format for the levels in my game - as part of this, I'm including a tag that should let me include a script for the given level:
/* given a text asset, this function finds lines beginning with EVENT;
and attaches the component with the name given after the semicolon */
function LoadSituation (target : TextAsset) {
var rawLines : String[] = target.text.Split("\n"[0]);
for(var line : String in rawLines){
if (line.StartsWith("EVENT")){
this.gameObject.AddComponent(line.Split(";"[0])[1].ToString());
}
}
}
However, when I test this function with the test line:
EVENT;DemoMatch
I get this error:
Can't add component because class 'DemoMatch' doesn't exist!
UnityEngine.GameObject:AddComponent(String)
SituationLoader:LoadSituation(TextAsset) (at Assets/Scripts/SituationLoader.js:35)
SituationLoader:Start() (at Assets/Scripts/SituationLoader.js:10)
Adding "DemoMatch" as a component the ordinary way (AddComponent("DemoMatch") ) works - however, using the same string from the text file doesn't, even when the strings are seemingly equivalent.
Is there any reason I can't add components like this, or am I simply making a mistake somewhere?
Answer by Eric5h5 · Jun 16, 2011 at 11:18 PM
No doubt DemoMatch has a carriage return character at the end (namely, '\r'
). You can use String.Trim() to get rid of that. (By the way, since "line" is already a string, you don't need to use ToString() on it.)
Yeah, common problems: carriage returns, line feeds or spaces...