Module code examples

From Kerbal Space Program Wiki
Revision as of 03:06, 8 March 2012 by Zool (talk | contribs)
Jump to: navigation, search

Here is a collection of example code for various tasks you might want to perform in your module.


Creating a GUI Window and Button

This module will create a new GUI window and button, on button press the part will explode, close the GUI, and be removed.

using UnityEngine;
 
/*
This module will create a new GUI window and button, on button press the part will explode, close the GUI, and be removed.
*/
	public class SelfDestruct : Part
	{
		protected Rect windowPos;
 
		private void WindowGUI(int windowID)
		{
        	GUI.DragWindow(new Rect(0, 0, 10000, 20)); //create a dragable window
       	 	GUIStyle mySty = new GUIStyle(GUI.skin.button); 
       		mySty.normal.textColor = mySty.focused.textColor = Color.white;
      		mySty.hover.textColor = mySty.active.textColor = Color.yellow;
      		mySty.onNormal.textColor = mySty.onFocused.textColor = mySty.onHover.textColor = mySty.onActive.textColor = Color.green;
      		sty.padding = new RectOffset(8, 8, 8, 8);
		 //It seems you need to put all buttons between vertical or horizontal GUILayout functions
		 //Without doing this GUILayout.Button() will only be true if you right and left click at the same time
		GUILayout.BeginVertical();
			if (GUILayout.Button("DESTROY",mySty,GUILayout.ExpandWidth(true)))//GUILayout.Button is "true" when clicked
			{	
			this.explode();
			this.onPartDestroy ();
			this.Die ();
			}
		GUILayout.EndVertical();
 
		}
		private void drawGUI()
		{
            GUI.skin = HighLogic.Skin;
            windowPos = GUILayout.Window(1, windowPos, WindowGUI, "Self Destruct", GUILayout.MinWidth(100));	 
		}
		protected override void onFlightStart()  //Called when vessel is placed on the launchpad
		{
		    RenderingManager.AddToPostDrawQueue(3, new Callback(drawGUI));//start the GUI
		}
		protected override void onPartStart()
		{
       		if ((windowPos.x == 0) && (windowPos.y == 0))//windowPos is used to position the GUI window, lets set it in the center of the screen
			{
          	  windowPos = new Rect(Screen.width / 2, Screen.height / 2, 10, 10);
   			}
		}
	 	protected override void onPartDestroy() 
		{
			RenderingManager.RemoveFromPostDrawQueue(3, new Callback(drawGUI)); //close the GUI
   		}
 
	}