Search code examples
c#unity-game-engineuser-interfacebuttonprefab

How to activate and access GameObjects from inside a Prefab (with a button)


I am currently trying to build a shop for my game. The shop is a list, that will be displayed onscreen and consists of Prefabs that each have a button component. On click, a hidden panel should be visible and different UI elements should be adjusted. I know that you can't directly reference GameObjects from a prefab, and I tried workarounds like a reference script from the actual scene and I am worried that using FindObjectsOfTypeAll() will be too slow, especially if I want to extend my game later on.

Below you can see my code:

public void LoadStore(PrisonerObject _prisObj)
    {
        //Here I am trying to get the references from a seperate script
        GameObject Panel1 = reference.ReturnShopPrisonerContainer();
        Panel1.SetActive(false);

        GameObject Panel2 = reference.ReturnPrisonerPreviewContainer();
        Panel2.SetActive(true);
    }

//This code is in a different Script
public GameObject ReturnShopPrisonerContainer()
    {
        ShopPrisonerContainer = GameObject.Find("ShopPrisonerContainer");
        return ShopPrisonerContainer;
    }

    public GameObject ReturnPrisonerPreviewContainer()
    {
        PrisonerPreviewContainer = GameObject.Find("PrisonerPreviewContainer");
        return PrisonerPreviewContainer;
    }

The LoadStore method will be called when the Button (on the prefab) is pressed. I read a lot about this problem, but I can't seem to find a suitable solution for my problem here. I found someone saying there is a different approach to this problem, but unfortunately he didn't really explain his alternative approach. Does anyone have any ideas how I can fix this?


Solution

  • As I understand you need to activate game object after clicking on the game object created from prefab. If yes you can just set listener on prefab's button

    // monobehavior on scene that creates objects from prefabs
    class PrefabCreator : MonoBehaviour
    {
        ...
        private void InstantiatePrefab(GameObject prefab)
        {
            var obj = Instantiate(prefab, ...);
            obj.GetComponent<Button>().OnClick.AddListener(OnClick);
        }    
    
        private void OnClick()
        {
            // click handling
        }
    }