Modifying mass of all objects
Hello!
I am having a rather strange problem at the moment with one of my Unity programs. The issue is that I need to define mass in terms of kinetic energy, so whenever a script or physics function requests for the objects mass, the object gives it's mass as normal. However, on every single object in the scene (except things such as the light or camera), I need to set my object's mass to 0.5*mass*(velocity^2), or set it's mass to it's kinetic energy. While this on it's own is pretty straight forward, i need to add this simple code to EVERY SINGLE OBJECT in the scene that has a rigid-body. I have very large number of objects, and adding everything manually would take forever. Can anyone please suggest a way I can do this via an external piece of code?
The code to add to every object is:
using UnityEngine;
public class MassEquivalenceScript : MonoBehaviour {
private Rigidbody rb;
private float startingMass;
void Start () {
rb = gameObject.GetComponent<Rigidbody> ();
startingMass = rb.mass;
}
void Update () {
float velocity_Squared = Mathf.Pow (rb.velocity.x, 2) + Mathf.Pow (rb.velocity.y, 2) + Mathf.Pow (rb.velocity.z, 2);
float velocity = Mathf.Sqrt(velocity_Squared);
rb.mass = 0.5f * startingMass * Mathf.Pow(velocity,2);
}
}
I was thinking something along these lines might do:
using UnityEngine;
public class CopyToAll : MonoBehaviour {
void Start () {
GameObject[] allObjects = somehow_Get_All_Objects_In_Scene;
foreach (GameObject item in allObjects) {
if (item.has_A_Rigidbody) {
Add_The_MassEquivalenceScript_Code_To_GameObject_Item
}
}
}
}
Thanking you all in advance!
Answer by Priyanka-Rajwanshi · Jul 06, 2018 at 12:39 PM
Put all the gameobjects on which you want to add the script under a single parent and use
public Transform allParent;
for(int i = 0; i < allParent.childCount; i++){
if(allParent.GetChild(i).GetComponent<Rigidbody>() != null){
//Your code
}
}