I want to enable gravity on a cube, if my character walks over it.
Any idea what kind of script i have to write?
I know i have to add a rigedbody to my GameObject, in this case the cube.
And that i need to add some kind of trigger to let it interact between the player and the cube.
var cube : UnityEngine.GameObject;
{
cube.rigidbody.useGravity = true;
}
I don’t really understand scripting yet, and i want to understand it more.
So can someone make an example on how this works?(java or C# doesn’t matter, prefer C#) or direct me to a site or page where i can understand this better?
-Thanks for your time to read this, i hope you can help me.
You could do the following: add a sphere collider to the cube (menu Component/Physics/Sphere Collider - click Add in the “Replace existing component?” dialog) and set its Is Trigger field, then set its Center/Y coordinate to 1 to place it above the cube. Add the following script to the cube:
using UnityEngine;
using System.Collections;
public class TurnGOn : MonoBehaviour {
void OnTriggerEnter(Collider other) {
if (other.tag == "Player"){ // if player entered the trigger...
rigidbody.useGravity = true; // turn gravity on
}
}
}
Notice that the player must be tagged “Player” for this to work.
Obviously, the cube should have a rigidbody (menu Component/Physics/Rigidbody) with its Use Gravity unchecked. There’s a problem, however: if something hits the cube, it will start moving and spinning around crazily. You could avoid this by using Is Kinematic instead of Use Gravity: let Use Gravity set and set Is Kinematic, then clear it in OnTriggerEnter:
...
if (other.tag == "Player"){ // if player entered the trigger...
rigidbody.isKinematic = false; // turn rigidbody on
}
...
A kinematic rigidbody doesn’t react to collisions or gravity - it’s much like a “turned off” rigidbody, which “turns on” when rigidbody.isKinematic is set to false.
One way you could do this would be to have on your cube a rigidbody, a cube collider and another collider to be a trigger. You can move and scale the trigger collider to be just above the cube for the player to walk into.
In the inspector on the cube’s rigidbody, you want ‘Use Gravity’ to be unticked and ‘Is Kinematic’ to be ticked. This way, the cube won’t fall initially.
Then add a script with the following (C#) to your cube:
This should make it so that once the player has moved into the trigger, the cube should now respond to gravity. Make sure to add a tag called “Player” to your player character and make sure your player character has some kind of collider attached to it.
You may want to add a small delay between the player entering the trigger and the cube falling. You can do this with a simple timer variable and a boolean. Attach this to the cube instead: