- Home /
Test if object has a certain script.
I want something to happen to an object IF it has a certain script on it. The code will be in affect on almost every object in the game, but this effect is only to affect those that have the script. I feel there should be an easy way to test for this, but I cannot find it.
How should I do this?
Answer by Bunny83 · Jan 27, 2011 at 08:41 AM
To correct Mike's answer, the C# version would be:
YourScript script = yourObj.GetComponent<YourScript>();
if (script != null)
{
//do stuff with script
}
Because you always have to specify a type in C# and "var" doesn't exist in C#.
For JS version you can just use
var script = yourObj.GetComponent(YourScript);
[...]
or a bit better: when you specify a fix type in JS the access to this var is faster
var script : YourScript = yourObj.GetComponent(YourScript);
[...]
Don't forget the generic version of GetComponent doesn't work on iPhone. Generic is everything with < Type>. In C# without generic you have to use:
YourScript script = (YourScript)yourObj.GetComponent(typeof(YourScript));
or
YourScript script = yourObj.GetComponent(typeof(YourScript)) as YourScript;
Hm. Thank you very much for this piece of information. Er... How am I supposed to place the "Correct Answer" thingie when there are several people that helped me?
Answer by Mike 3 · Jan 27, 2011 at 08:08 AM
js:
var script = yourObj.GetComponent.<YourScript>();
if (script != null)
{
//do stuff with script
}
c#:
var script = yourObj.GetComponent<YourScript>();
if (script != null)
{
//do stuff with script
}
Only difference is a single . but it makes it more explicit
Thank you very much. I am using the js one. One less noob problem I will hopefully never have... ;)