Run component methods directly from inspector
Unity doesn't have a quick way to add buttons to existing inspectors, but there's the ContextMenu attribute that you can add in front of a method to add this menu to the context menu of this component. If you add this to your method, then you can simply right-click on the component in the Unity inspector and this option will be available directly from the context menu.[ContextMenu("Start Game")]
private void StartGame()
{
Debug.Log("Starting game...");
}
Add buttons to standard inspector
There are several Asset Store packages that will allow you to modify the default inspectors (like for example the omnipotent Odin Inspector and Serializer).But if you don't want to add a big package to your project just to add a single button to an inspector, then you can do something similar with a small custom class:
Create a new class (you can add an Editor suffix to its name) and put it in an Editor subfolder (so that it doesn't get compiled into the final build).
Add the following content to the class, but take care to adapt the class names according to the class you're trying to call.
Finally add normal GUILayout.Button calls for each button you want to add and call the corresponding method via the component variable.
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
// indicate that this editor class belongs to the Game class.
[CustomEditor(typeof(Game))]
public class GameEditor : Editor
{
public override void OnInspectorGUI()
{
// draws the default inspector, so your buttons follow beneath.
DrawDefaultInspector();
GUILayout.Space(16);
// this gets a reference to your actual class via which you can call your methods.
Game component = (Game)target;
// draw all buttons in one horizontal line
GUILayout.BeginHorizontal();
// render button that calls your StartGame method
if (GUILayout.Button("Start Game"))
{
component.StartGame();
}
// render button that calls your StopGame method
if (GUILayout.Button("Stop Game"))
{
component.StopGame();
}
// finish horizontal line
GUILayout.EndHorizontal();
}
}