Applying gravity to prefabs via a script

Hi All,

I’m new to Unity and this is my first ever post. Absolutely loving the engine so far and having a lot of fun experimenting with its features. I was wondering if someone could give me some guidance. Using c# I have written a simple script to instantiate a number of prefabs in my scene. Initially my prefabs are kinetic with no gravity. I want to allow them to draw in the scene then via a key press enable the gravity and disable the fact they are kinetic.

I have literally just added this very simple code to do so (where fixedPoint is the name of my prefab) :

if (Input.GetKeyDown("g"))
		{
			fixedPoint.GetComponent<Rigidbody>().isKinematic = false;
			fixedPoint.GetComponent<Rigidbody>().useGravity = true;
				
		}

This seems to work fine for any prefabs that are yet to be rendered to the scene. I was hoping to allow my prefabs to be drawn and then by clicking the ‘g’ key allow gravity to take effect for all of the prefabs in the scene.

Can anyone assist?

Thanks

Rob

Welcome to the forums :slight_smile:

It sounds like you’re modifying the prefab itself and expecting (or maybe just hoping :slight_smile: that all instances that have been cloned from the prefab will be affected.

However, this isn’t how it works. (At least not AFAIK - to be honest, I haven’t tried it myself.) It’s kind of like if you drew a picture, made a copy of the picture, and then scribbled something on the original picture; the copy would not be affected, and similarly, an instance cloned from a prefab will not be affected by changes made to the prefab after the fact (IINM).

What you probably want to do is to modify the actual cloned instances themselves. There are various ways you can track and access said instances for this purpose, including storing references to them in a container as they’re created, or searching for them by name, tag, or type.