Home > OS >  How to reset the position of object to their start position?
How to reset the position of object to their start position?

Time:09-09

at some point, I want to reset all objects with the PhysicsObject script attached to their first position.

public class PhysicsObjects : MonoBehaviour
{
    public float waitOnPickup = 0.1f;
    public float breakForce = 35f;
    [HideInInspector] public bool pickedUp = false;
    [HideInInspector] public Interactions playerInteractions;
    Vector3 originalPosition;
    Quaternion originalRotation;
    public Rigidbody rigidbody; 
    private void Start()
    {
        originalPosition = transform.position;
        originalRotation = transform.rotation;
    }
    private void OnCollisionEnter(Collision collision)
    {
        if (pickedUp)
        {
            //collision.relativeVelocity.magnitude > breakForce
            if (collision.relativeVelocity.magnitude > breakForce)
            {
                 playerInteractions.BreakConnection();
                
            }           
        }  
    }

    public void ResetObjects()
    {
       transform.position = originalPosition;
        transform.rotation = originalRotation;
        if (rigidbody != null)
        {
            rigidbody.velocity = Vector3.zero;
            rigidbody.angularVelocity = Vector3.zero;
        }
    }
}

and in my other Script:

 PhysicsObjects Physics;  
 private void Start()
    {
        GameObject inter = GameObject.Find("SeatPillow");
        Physics = inter.GetComponent<PhysicsObjects>();
    }
.... 
Physics.ResetObjects();  

I tested this only for one object which is SeatPillow and it worked as I specified this object here: GameObject inter = GameObject.Find("SeatPillow");, How would I make this work for all the objects with PhyiscsObject attached without having to specify each one of them?

CodePudding user response:

Create List of PhysicsObjects and populate it when Instantiating desired objects, then use foreach to operate on all of them - physicsObjectsList.ForEach(x => x.Reset());

note: if you are not instantiating those objects from scripts then create public (or [SerializeField] private) list and drug and drop all desired objects from scene to that "other Script" component

  • Related