简体   繁体   中英

Can't find objects with Find() in hierarchy

When game starts, script will close the shop.(SetActive(false))

void Start()
    {
        _shopMenu = GameObject.Find("Shop");

        _shopMenu.SetActive(false);

        if (_shopSlotContainer == null || _shopItemSlotTemplate == null)
            FindItemShopContainerAndItemTemplate();
    }

And try to find two objects on scene

private void FindItemShopContainerAndItemTemplate()
    {
        _shopSlotContainer = transform.Find("itemShopContainer");

        if (_shopSlotContainer == null)
            Debug.LogError("Container doesn't found");

        _shopItemSlotTemplate = transform.Find("shopItem_template");

        if (_shopItemSlotTemplate == null)
            Debug.LogError("Item template doesn't found");
    }

在此处输入图像描述

Any other ways to find objects or fix this problem? (Script attached to "Shop" object)

Transform.Find will only search the immediate children, it will not look further down in the hierarchy. It is also not very performant. You can assign the game objects you want to variables in your script

public class MyScript : MonoBehavior
{
   [SerializeField]
   private GameObject _itemShopContainer {get; set;}
}

After compile you should be able to see Item Shop Container property on MyScript game object in the editor and be able to drag the proper game object there. In the code _itemShopContainer will now have your game object.

If you want to assign via code like you are doing switch to using a variant of Transform.GetComponentsInChildren<>(), rather than Transform.Find

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM