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?
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;
Mike_3
January 27, 2011, 8:08am
2
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