Search code examples
c#unity-game-enginegameobjectrigid-bodies

Assign multiple Rigidbodies to function


I'm working on a Unity + Vuforia app that works on a specific box of wine. there a tap on the side, when you click on it, spheres start dropping from it as if liquid. i made a script that gives gravity to a sphere at a click on the tap.

[SerializeField] 
private Rigidbody sphere;
public Collider tap;

void Start()
{
    
    tap = GetComponent<Collider>();
}

void OnMouseDown()
{
    if (sphere.useGravity == false)
    {
        Debug.Log("Flows");
        sphere.useGravity = true;
        sphere.isKinematic = false;
    }

    else if (sphere.useGravity == true)
    {
        Debug.Log("Stops");
        sphere.useGravity = false;
        sphere.isKinematic = true;
    }
}

A sphere is assigned to the sphere variable, what i want is for the inspector to have a field where i can enter how many spheres i want attached, and then attach them manually. Instead of making a variable for each of the spheres. If there is another way of doing this please let me know.

To summarize: I want several rigidbodies to useGravity on one click.


Solution

  • You can make a list of rigidbodies like public List<RigidBody> bodies, but you need to assign all your spheres to the list using bodies.Add(rb) The effect you are achieving is then in the single frame where the OnMouseDown() function is called. It will loop through the list using foreach

    [SerializeField] 
    private List<Rigidbody> bodies;
    public Collider tap;
    
    void Start()
    {
        tap = GetComponent<Collider>();
    }
    
    void OnMouseDown()
    {
        if (sphere.useGravity == false)
        {
            foreach (Rigidbody body in bodies)
            {
                body.useGravity = false;
                body.isKinematic = true;
            }
        }
    }