Hi, I’m wondering what syntax I need to use to find out which scripts are attached to a given GameObject.
Question is about as simple as what’s on the tin, I think.
Hi, I’m wondering what syntax I need to use to find out which scripts are attached to a given GameObject.
Question is about as simple as what’s on the tin, I think.
var scripts = GetComponents (MonoBehaviour);
–Eric
GetComponent() is also useful, depending on if you want all Components or just MonoBehaviours.
The question was about finding all attached scripts, though. The point being you can’t have scripts attached to objects that aren’t derived from MonoBehaviour.
–Eric
Thanks for the advice, but, when I try this, it throws the error “‘MonoBehaviour’ is a type, which is not valid in the given context”. I threw this inside Start(), for reference.
Works fine here.
–Eric
Somehow I doubt that
It should be either:
var scripts = GetComponents<MonoBehaviour>();
or
var scripts = GetComponents(typeof(MonoBehaviour));
I recommend using the first version; it will make your life a little easier.
I wouldn’t have posted it if it didn’t work, nor would I say it works fine if it didn’t. I wasn’t posting C#, though.
–Eric
Welllllll if you’re a moderator you should be aware of the “Code (CSharp)” header that the code tag defaults to AND that all the cool kids use C# these days anyway.
You’re right about one of those two things. I wasn’t paying attention to the code tag header. Although it should be fairly obvious from the code itself.
–Eric
To be honest if you added in a typeof operator, that code would be valid C# code as well. and seeing as most code on this forum is C# (unless Javascript was explicitly asked for) and forgetting a typeof is something I do from time to time, its more likely that people will simply think that code is C# with a typo.
It would not work with a typeof, there’d be a cast missing.
@Eric5h5 , OP doesn’t know how to grab MonoBehaviours off a gameObject. You can’t assume that they’ll tell C# and UnityScript apart at a glance.
With Unity shifting all tutorials and docs to C#, posting advice to obvious beginners in UnityScript is not a great idea. Most of the time you’ll be causing unnecessary confusion.
The OP has been around since 2015; I wouldn’t make any assumptions about beginners or not just based on this question. The only confusion was that I neglected to use the correct code tag header.
–Eric
Your war neads to be an array like:
var[] varName = GetComponents<MonoBehavior>()
//then you can use the first script on your game object with:
varName[0]
//the second
varName[1]
//just like an array
Please don’t necro post; this thread is over 6 years old and has already been resolved above with code that works/compiles. Your suggestion is wrong and won’t compile. You don’t use “var[ ]” you’d use “var” and “MonoBehavior” is spelt “MonoBehaviour”.
Thanks.