Question is off-topic or not relevant
C# Get specific component of gameobject
I have multiple WheelJoint2D components on a gameobject. How would I go about removing a specific one of those WheelJoint2Ds?
What you could do is declare public variables :
public WheelJoint2D wj1; public WheelJoint2D wj2;
And then destroying the one you want.
I have made an array of all the WheelJoint2Ds of the gameobject, what do I do now?
Answer by jdean300 · Jul 18, 2016 at 06:08 PM
Unless you maintain a reference to each component such as:
public class MyComponent : MonoBehaviour{
public WheelJoint2D WheelJointOne; //You can set this from the inspector
public WheelJoint2D WheelJointTwo; //You can set this from the inspector
}
The best you can do is get all instances of that component and then filter the results based on known properties:
public void SomeFunction(){
WheelJoint2D[] wheels = GetComponents<WheelJoint2D>();
foreach (WheelJoint2D w in wheels){
//Find the joint that matches some parameters, then you can delete it.
}
}
The filtering method is not ideal because it can be pretty hard to differentiate between two instances of a component some times, but it is possible in some cases. Assigning references within the inspector using public variables is really the easiest way to get things right.
How exactly do I delete it? I have made an array that stores all the wheeljoints on the gameobject and called it "wheels" I made a loop and checked if it matched the one I was looking for, and called the int for it "i"
Destroy (wheels[i]);
This results in the error: "Argument is out of range."
Can you show us the loop script? Also what helps is if you print(wheels[i])
for (int i = 0; i < wheels.Count; i++){
if (wheels[i].connectedBody == hit.transform.GetComponent<Rigidbody2D>()){
Destroy (wheels[i]);
}
}