Skip to content

Instantly share code, notes, and snippets.

@beardordie
Created August 18, 2018 19:34
Show Gist options
  • Save beardordie/cd1beff5863169c291b6cbf36a90d778 to your computer and use it in GitHub Desktop.
Save beardordie/cd1beff5863169c291b6cbf36a90d778 to your computer and use it in GitHub Desktop.
Unity Editor-only helper script to simulate gravity for placing objects on ground with physics
#if UNITY_EDITOR
using System.Collections;
using UnityEditor;
using UnityEngine;
[ExecuteInEditMode]
public class SimulateGravity : MonoBehaviour
{
public bool simulate = false;
public bool remove = false;
new Rigidbody rigidbody;
private void OnValidate()
{
rigidbody = GetComponent<Rigidbody>();
if (!rigidbody) Debug.Log("Cannot simulate gravity without a rigidbody");
if(!simulate && !remove) StartCoroutine(SimulateCoroutine());
}
void Update()
{
if(remove)
{
Physics.autoSimulation = true;
DestroyImmediate(this);
}
if (!simulate) return;
Physics.autoSimulation = false;
Physics.Simulate(Time.deltaTime);
}
[MenuItem("Tools/SimulateGravity")]
public static void StartSimulateGravity()
{
Rigidbody selectionRigidbody = Selection.activeGameObject.GetComponent<Rigidbody>();
if (!selectionRigidbody)
{
Debug.LogError("Cannot simulate gravity on a gameobject without a rigidbody");
return;
}
Selection.activeGameObject.AddComponent <SimulateGravity> ();
}
IEnumerator SimulateCoroutine()
{
simulate = true;
yield return new WaitForSeconds(1f);
simulate = false;
remove = true;
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment