Search Unity

[Custom Inspector] Create an ObjectField by pressing a button

Discussion in 'Scripting' started by Krisztian, Jul 30, 2014.

  1. Krisztian

    Krisztian

    Joined:
    Jul 30, 2014
    Posts:
    2
    Greetings,

    I'm trying to create an ObjectField by pressing a button, but without any success.
    Currently I'm doing it somehow like this:

    Code (JavaScript):
    1.                     if(GUILayout.Button("Objectfield")){
    2.                      
    3.                         objfield = EditorGUILayout.ObjectField("Object: ", objfield, AudioClip, false);
    4.                  
    5.                     }
    Should this even work? Because if it's not, the problem is somewhere else in my script.
    Oh, and no errors at all.

    Thanks for any help.
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    The Button will only return true for one "frame" (since "frames" in the editor generally last until the next interaction from the user, this may sorta work in a hackish way). The proper way to do it would be a boolean flag:
    Code (csharp):
    1.  
    2. private float doShowObjectField = false;
    3. void OnInspectorGUI() {
    4. //....
    5. if (doShowObjectField) {
    6. objfield = EditorGUILayout.ObjectField("Object: ", objfield, AudioClip,false);
    7. }
    8. else {
    9. if (GUILayout.Button("ObjectField")) {
    10. doShowObjectField = true;
    11. }
    12. }
    13.  
    In this particular case, though, why have a button at all? A blank ObjectField would surely serve the same purpose as a button, with less complication and less clicking? Unless of course this example is your "test case" and you're actually making something more complex.
     
  3. Krisztian

    Krisztian

    Joined:
    Jul 30, 2014
    Posts:
    2
    Thanks for reply.

    Yeah, I'm still learning and wanted to test some things out. Actually I wanted to make a button that creates an ObjectField every time you press it, but I think I will figure it out now. Thanks for help.
     
  4. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    In that case, your approach depends on what the ultimate destination is of the objects being assigned in these fields. Are they going into an array on the object? If that's the case, then clicking the button should expand the array itself; and you loop through the array's object and display an ObjectField for each array index.