- Home /
How can i add a button to the inspector ?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NodesGenerator : MonoBehaviour {
public GameObject NodePrefab;
public int NodesNumberX = 16;
int NodesNumberY;
void Generate()
{
for (int x = 0; x < NodesNumberX; x++)
{
for (int y = 0; y < NodesNumberY; y++)
{
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.transform.localScale = new Vector3(4, 1, 4);
cube.transform.position = new Vector3(x * 5, 0, y * 5);
}
}
}
private void OnGUI()
{
if (GUILayout.Button("Generate Nodes"))
{
NodesNumberY = NodesNumberX;
Generate();
}
}
}
When i attach the script to a gameobject i want to see in the script in the inspector:
The OnGui add the button to the game screen when running the game. But i want to add the button to the Inspector for example like the button Add Component. This kind of button.
Answer by tomazsaraiva · Apr 10, 2017 at 06:02 AM
You need to create a custom inspector for your component.
building custom inspector adding buttons to the custom inspector
Answer by Guedez · Jan 16, 2020 at 07:13 PM
you can use a bool field and read it's value on OnValidate, execute the action, and set the bool back to false
Here is a helpful link since the unity documentation for this function does not have any example currently (June 2020): http://cjf.in.ua/812-unity-editor-extensions-the-power-of-onvalidate/
Here is example usage:
//>>> Add in the begining of your script it is required if you would like to do different stuff in playmode for some reason
#if UNITY_EDITOR
using UnityEditor;
#endif
public void LoadData(){
#if UNITY_EDITOR
if (!EditorApplication.isPlaying) {
//Do stuff only when in editor and not in playmode
return;
} else {
//Do stuff you would normally do
}
#endif
}
//<<< End of EditorApplication.isPlaying check
//Declare bool that will be used as a "button", it's best used with preprocessor directive so you don't have this in final build
#if UNITY_EDITOR
public bool reloadInitialData = false;
//You can have multiple booleans here
private void OnValidate() {
if (reloadInitialData) {
// Your function here
LoadData ();
//When its done set this bool to false
//This is useful if you want to do some stuff only when clicking this "button"
reloadInitialData = false;
}
}
#endif
I know it is an old thread but one that was most useful for me, thanks for tip Guedez
Your answer
Follow this Question
Related Questions
How do i use a public sealed class to create objects and destroy them ? 0 Answers
How can I call the Load method and/or the ShootingSettings method also only once in the Update ? 1 Answer
How can i check and fire an event when the user look at specific object ? 0 Answers
How can i List objects by name but also in small text or big text or any kind ? 1 Answer