Skip to content

Instantly share code, notes, and snippets.

@openroomxyz
Last active July 14, 2020 11:15
Show Gist options
  • Save openroomxyz/b8f03eeb07c988def2ca46a5d872d3a2 to your computer and use it in GitHub Desktop.
Save openroomxyz/b8f03eeb07c988def2ca46a5d872d3a2 to your computer and use it in GitHub Desktop.
Unity : How can i run a script in in edit mode (Not Runtime) when i select some object, and i wish to receive user input (Edit update loop) and Instantiate and object on key-press ?
using UnityEditor;
using UnityEngine;
//How can i run a script in at at edit time (Not Runtime) when object is selected, and recive user input (Edit update loop) ?
//Editor scripts have to be in folder named Editor
//[CustomEditor(typeof(GameObject))] ensures that this peace of code will run only when we have GameObject selected so we are save to cast object to GameObject [selectedTarget = (GameObject)target;]
[CustomEditor(typeof(GameObject))] //This is custom editor for the type GameObject ( This script will kick in when we have game object selected )
public class CubeEditor : Editor
{
private GameObject selectedTarget;
const float radius = 4f;
//This functions runs only one when we click the object.
private void OnEnable() //Similar to start in MonoBehavior
{
//this will be always be true ( we are safe of doing this cast )
//The target is the keyword suplied by the Editor class and it means the selection
selectedTarget = (GameObject)target;
SceneView.duringSceneGui += CustomUpdate;
}
private void OnDisable()
{
SceneView.duringSceneGui -= CustomUpdate;
}
public override void OnInspectorGUI() //this method is run several times a frame as soon there is a change in the scene
{
base.OnInspectorGUI();
Debug.Log(selectedTarget.name);
}
void CustomUpdate(SceneView cv) //out custom function, ran every frame frame during Unity's editor (to achive this we add it to delegate)
{
//Debug.Log("CustomUpdate has been tied to the SceneView.duringSceneGui delegate!");
Event e = Event.current; //It'can be anything
if(e.isKey && e.character == 'g')
{
GameObject instanciatedCube = (GameObject)PrefabUtility.InstantiatePrefab(Resources.Load("Cube"));
//instanciatedCube.transform.position = selectedTarget.transform.position + Random.insideUnitSphere;
instanciatedCube.transform.position = selectedTarget.transform.position + (Quaternion.Euler(Random.Range(-180.0f, 180.0f), Random.Range(-180.0f, 180.0f), Random.Range(-180.0f, 180.0f))) * Vector3.forward * Random.Range(0.1f, radius);
//When dealing with quaternions the order of operation is important in multiplication
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment