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.

1 Answer

1

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*);* This results in the error: "Argument is out of range."