Hi all,
I’ve only been learning C# for about a week so bear with me here…
I create a sphere and I just want it to hang in space, this is my code:
void Start ()
{
for (int y = 0; y < 1; y++) {
for (int x = 0; x < 1; x++) {
GameObject sphere = GameObject.CreatePrimitive (PrimitiveType.Sphere);
sphere.AddComponent<Rigidbody> ();
rigidbody.useGravity = false;
sphere.transform.position = new Vector3 (0, 0, 0);
}
}
}
I figured that the useGravity bit would stop it from falling, but after creating it, it’s still got Gravity enabled until I pause it and turn it off, anyone know how to just make it hang there without falling?
Thanks!
I have tested your code and it works.
Look if you have added the script to the sphere and also the rigidbody. You can also set the is Kinematic true.
Hope this helps
I’m not 100% on this but I’m sure that you can’t disable gravity on the next line as the RigidBody won’t be created until the next frame. I could be wrong.
Try something like this directly after addcomponent to test the theory:
if(rigidbody)
{
rigidbody.useGravity = false;
Debug.Log("Rigidbody exists");
}
else
Debug.Log("NO rigidbody");
I’m guessing its because the added component isn’t initialized yet (it takes longer for AddComponent to finish setting up than for the script to continue and set useGravity). Try getting a reference to the added component and change it there :
GameObject sphere = GameObject.CreatePrimitive (PrimitiveType.Sphere);
sphere.AddComponent<Rigidbody>();
Rigidbody rBody = sphere.GetComponent<Rigidbody>();
rBody.useGravity = false;
sphere.transform.position = new Vector3 (0, 0, 0);
You need to add collider.