How to add a script to an object via another script

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 certain objects in the scene, I need to set my object’s mass to 0.5mass(velocity^2), or set it’s mass to it’s kinetic energy so that my game calculates things correctly. While this on it’s own is pretty straight forward, there is a problem. The objects are being produced by a script, so I can’t just go into the editor and add the scripts to the objects, as they are produced while in-game. The script has the GameObject defined under the name newObject and that all works, I just need to know ultimately how to add a script to a GameObject via another script.

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);
	}
}

In summary, I need to know how to attach the above script to a GameObject via another script. I don’t need the entire script to be done, I just need the code for this.

Thanking you all in advance! :slight_smile:

@Technokid2000
Use this:

  newObject.AddComponent<MassEquivalenceScript>();

Thankyou! It worked first time. For some reason when i tried the first few times it was throwing an error, but it works now!

Good day.

You only need to add it like any other component… Go read some manual/tutorial.

Bye!