Метод не работает внутри метода onGUI () - PullRequest
0 голосов
/ 26 июня 2019

Я хочу написать метод, который может вызывать метод onGUI ().

Я написал этот метод. Однако, когда я запускаю программу, метод не показал эффекта.

    private void ShowSubPartsOnClick(float x, float y, float widthLABEL, float heigth, HumanBodyPart bodyPart)
    {

        x = x + 14;

        for(int i = 0; i < bodyPart.SubParts.Count; i++)
        {

            y = y + 14;
            GUI.Label(new Rect(x+14,y,widthLABEL,heigth), bodyPart.SubParts[i].EnglishTitle);

            if(GUI.Button(new Rect(x, y, 14, heigth),"+"))
            {
                ShowSubPartsOnClick(x, y, widthLABEL, heigth, bodyPart.SubParts[i]);
            }
        }
    }

}


  private void OnGUI()
    {
        GUI.Label(new Rect(text.transform.position.x+14, text.transform.position.y, text.rectTransform.sizeDelta.x, 14),bodyVisualizer.BodyData.Body.SubParts[0].EnglishTitle);

        if(GUI.Button(new Rect(text.transform.position.x, text.transform.position.y, 14, 14), "+"))
        {
            ShowSubPartsOnClick(text.transform.position.x, text.transform.position.y, text.rectTransform.sizeDelta.x, 14, bodyVisualizer.BodyData.Body.SubParts[0]);
        }


    }


Как я могу это исправить или в чем проблема?

1 Ответ

2 голосов
/ 26 июня 2019

Проблема здесь в том, что такие функции, как GUI.Label и GUI.Button, должны вызываться напрямую из OnGUI для работы:

Из форумов Unity : «Единственное место, где вы можете рисовать / создавать элементы графического интерфейса, - это запускать их из функции OnGUI».

Учитывая рекомендацию, одним из решений является запуск итеративного поиска в глубину через цикл while. Смотрите прикрепленный пример.

При этом я настоятельно рекомендую использовать Unity Canvas вместо OnGUI. Он гораздо мощнее, и его программная логика не ограничивается одной функцией.

Фрагмент OnGUI :

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class HumanBodyPart
{
    public string EnglishTitle;
    public List<HumanBodyPart> SubParts;
    public bool IsExpanded;
    public int DrawDepth;

    public HumanBodyPart(string title, HumanBodyPart[] subParts)
    {
        this.EnglishTitle = title;
        this.SubParts = new List<HumanBodyPart>();
        this.SubParts.AddRange(subParts);
        this.IsExpanded = false;
        this.DrawDepth = 0;
    }
}

public class Script : MonoBehaviour 
{
    [SerializeField]
    Text text;
    HumanBodyPart mainBodyPart;

    private void Start()
    {
        HumanBodyPart subSubSubBodyPart = new HumanBodyPart("SubSubSubBodyPart", new HumanBodyPart[] { });
        HumanBodyPart subSubBodyPart1 = new HumanBodyPart("SubSubBodyPart1", new HumanBodyPart[] { subSubSubBodyPart });
        HumanBodyPart subSubBodyPart2 = new HumanBodyPart("SubSubBodyPart2", new HumanBodyPart[] { });
        HumanBodyPart subBodyPart = new HumanBodyPart("SubBodyPart", new HumanBodyPart[] { subSubBodyPart1, subSubBodyPart2});
        mainBodyPart = new HumanBodyPart("BodyPart", new HumanBodyPart[] { subBodyPart });
        UpdateDrawDepths(mainBodyPart);
    }

    private void UpdateDrawDepths(HumanBodyPart currentBodyPart, int currentDrawDepth=0)
    {
        currentBodyPart.DrawDepth = currentDrawDepth;
        foreach (HumanBodyPart bodyPart in currentBodyPart.SubParts)
        {
            UpdateDrawDepths(bodyPart, currentDrawDepth + 1);
        }
    }

    private void OnGUI()
    {
        float spacing = 30;
        float x = text.transform.position.x + spacing;
        float y = text.transform.position.y;
        int drawDepth = 0;
        List<HumanBodyPart> nextPartsToRender = new List<HumanBodyPart>(new HumanBodyPart[] { mainBodyPart });
        while (nextPartsToRender.Count > 0)
        {
            HumanBodyPart currentPart = nextPartsToRender[0];
            GUI.Label(new Rect(currentPart.DrawDepth * spacing + x, y, 200, 20), currentPart.EnglishTitle);
            nextPartsToRender.RemoveAt(0);
            if (GUI.Button(new Rect(x - spacing + currentPart.DrawDepth * spacing, y, 20, 20), "+"))
            {
                currentPart.IsExpanded = true;
            }
            if (currentPart.IsExpanded)
            {
                nextPartsToRender.InsertRange(0, currentPart.SubParts);
            }
            y += spacing;
        }
    }
}

example code UI expanded

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...