- Home /
Getting Components with the same name
I am trying to create an object that can be affected by more than one joint at run-time. When a new object B is attached to my original object A, A adds a configurable joint to itself and takes B as its connected rigid body. The problem occurs when a new object C wants to attach itself to the original object A. A adds a new configurable joint to itself, but when I use the GetComponent() function to get the configurable joint, it returns the first joint created so changing the connected body that joint replaces B (i.e object C replaces B) and the joint created for C cannot be accessed leaving the connected body to be none. How can I reference the joint created for C without replacing that for B.
PS: Sorry the question sounds like a riddle that's the best way I can explain it
Answer by Mike 3 · Jun 20, 2010 at 04:44 PM
Use GetComponents instead, which returns an array you can loop through (or store the components yourself in an array when you do AddComponent, so you know which is which)
Answer by bimboladimeji · Jul 22, 2010 at 06:58 AM
For some reason gameObject.GetComponents(AudioSource) does not seem to return an array try casting whatever it returns into an array. This should work. Try this:
var mySfxAudioSources:AudioSource[];
function Start() { mySfxAudioSources = Array(gameObject.GetComponents(AudioSource)); }
Answer by Grimmy · Jul 21, 2010 at 11:31 AM
All I ever get when I try this is
InvalidCastException: Cannot cast from source type to destination type. AudioManagerScript.Start () (at Assets\MIHT_Assets\MIHT_Scripts\AudioManagerScript.js:27)
my code is:
var mySfxAudioSources:AudioSource;
function Start() { mySfxAudioSources=gameObject.GetComponents(AudioSource); }
I'm obviously doing something wrong but I dont know what. I have tried declaring a new array length too(mySfxAudioSources=new AudioSource(20)) but I still get the same problem.
I tried that and that got rid of the error but my mySfxAudioSources array still shows up as length 0 in the inspector..even though my gameObject has 3 audio sources attached. Any idea why?
Your answer
![](https://koobas.hobune.stream/wayback/20220613062538im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Can I make reference/assocation to another component as variable? 0 Answers
Changing script name displayed in inspector 3 Answers
Inspector:Reference a component in Assets, not in scene. 0 Answers
Multiple scripts with the same name issue 1 Answer
Best practice for assigning class reference at runtime? 0 Answers