[英]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. shop 是一个列表,将显示在屏幕上,由 Prefab 组成,每个 Prefab 都有一个按钮组件。 On click, a hidden panel should be visible and different UI elements should be adjusted.点击时,隐藏的面板应该是可见的,并且应该调整不同的 UI 元素。 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.我知道你不能直接从预制件中引用 GameObjects,我尝试了像实际场景中的引用脚本这样的变通方法,我担心使用 FindObjectsOfTypeAll() 会太慢,特别是如果我想稍后扩展我的游戏.
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.按下按钮(在预制件上)时,将调用LoadStore方法。 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?有谁知道我该如何解决这个问题?
As I understand you need to activate game object after clicking on the game object created from prefab.据我了解,您需要在点击从预制创建的游戏 object 后激活游戏 object。 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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.