Как проверить / найти скрытый или активный Gameobject, присутствующий в Transform? - PullRequest
0 голосов
/ 01 февраля 2019

Я нажимаю кнопку, в соответствии с которой на сцене появляются модели. Когда я снова нажимаю ту же кнопку, одна и та же модель появляется дважды. Как это остановить.то есть, если модель / Gameobject уже загружена, то нет необходимости загружать снова.

Я использую Gameobject.find здесь. Когда я нажимаю одну кнопку модели, появляется соответствующая модель, и другая модель, присутствующая в сцене, исчезает. На этот раз Gameobject.find не будет работать, поскольку другая модель скрыта. Лучшее решение. Пожалуйста, посмотрите на приведенный ниже код слишком много, если еще.:)

private string _assetname;

public void LoadAsstBundles(int choice)
{
    if (choice == 1)
    {
        _assetname = “Chair1”;
    }
    else if (choice == 2)
    {
        _assetname = “Chair2”;
    }
    else if (choice == 3)
    {
        _assetname = “Chair3”;

    }


    if (_assetsBundle == null)
    {
        Debug.Log("Could Not load AssetBundles");
    }
    else
    {


        if (GameObject.Find(_assetname + "(Clone)"))
        {
            Debug.Log("Already Loaded");
        }

        else
        {

            var asset = _assetsBundle.LoadAsset(_assetname);

            int childcounts = ParentTransform.childCount;

            Debug.Log("Asset name nw ==" + asset.name);


            Debug.Log("Asset Bundles Loaded");

            var go = (GameObject)Instantiate(asset, ParentTransform);

            int option = go.transform.GetSiblingIndex();


            int childcount = ParentTransform.childCount;

            for (int i = 0; i < childcount; i++)
            {

                if (option == i)
                {
                    ParentTransform.GetChild(i).gameObject.SetActive(true);
                    continue;
                }
                ParentTransform.GetChild(i).gameObject.SetActive(false);

            }

        }

    }

}

Ответы [ 2 ]

0 голосов
/ 01 февраля 2019

Вместо использования Find во всех случаях лучше работать с переменными, сохраняйте ссылки, которые вы получаете при создании экземпляров объектов, и используйте их позже, например,

// Here you store the reference from
// Assetbundle.LoadAsset
private object loadedAsset; 

// Here you store the reference to the assets instance itself
private GameObject assetInstance;

public void LoadAsstBundles(int choice)
{
    // Is _assetBundle available?
    if (!_assetsBundle)
    {
        Debug.Log("Could Not load AssetBundles", this);
        return;
    }  

    // Was the bundle loaded before?
    if (!loadedAsset)
    {
        loadedAsset = _assetsBundle.LoadAsset(_assetname);

        if(!loadedAsset)
        {
            Debug.LogError("unable to load asset", this);
            return;
        }

        Debug.Log("Asset Bundles Loaded", this);
    }

    // Is the object Instantiated in the scene?
    if(!assetInstance)
    {
        assetInstance = (GameObject)Instantiate(loadedAsset, ParentTransform);
        Debug.LogFormat(this, "Instantiated {0}", assetInstance.name);
    }

    // no need to go by names
    // simply get the correct child by index
    var selected = assetInstance.transform.GetChild(choice);

    // Enable or disable the childs
    // simply run through all childs no need to get their names etc
    foreach(Transform chair in assetInstance.transform)
    {
        chair.gameObject.SetActive(chair == selected);
    }
}
0 голосов
/ 01 февраля 2019

Я использовал Parenttransform.find, чтобы получить дочерние скрытые объекты. Немного длиннее. Любой обновленный код приветствуется.

public void LoadAsstBundles(int choice)
        {
            if(choice==1)
            {
                _assetname = "Chair1";
            }
            else if(choice == 2)
            {
                _assetname = "Chair2";
            }
            else if(choice == 3)
            {
                _assetname = "Chair3";

            }

    if (_assetsBundle==null)
    {
        Debug.Log("Could Not load AssetBundles");
    }
    else
    {

       var asset= _assetsBundle.LoadAsset(_assetname);

        //if (GameObject.Find(_assetname + "(Clone)"))
        //{
        //    Debug.Log("Already Loaded");
        //}


        if(ParentTransform.Find(_assetname+ "(Clone)")== true)
        {
            Debug.Log("Already Loaded");

            int childcount = ParentTransform.childCount;
            for (int i = 0; i < childcount; i++)
            {

                if (choice == i)
                {
                    ParentTransform.GetChild(i).gameObject.SetActive(true);
                    continue;
                }
                ParentTransform.GetChild(i).gameObject.SetActive(false);

            }


        }

        else
        {


            Debug.Log("Asset Bundles Loaded");

            var go = (GameObject)Instantiate(asset, ParentTransform);

            int option = go.transform.GetSiblingIndex();
            _loadednames.Add(go.name);




            Debug.Log("Sibling index == " + go.transform.GetSiblingIndex());

            int childcount = ParentTransform.childCount;

            for (int i = 0; i < childcount; i++)
            {

                if (option == i)
                {
                    ParentTransform.GetChild(i).gameObject.SetActive(true);
                    continue;
                }
                ParentTransform.GetChild(i).gameObject.SetActive(false);

            }


        }

    }

}
...