- Home /
Cannot attach GameObject to a button's On click enviroment within a prefab. Unity
So I have a prefab which containcs another prefab with a group of buttons. So in one of the buttons I want to attach on the onClick enviroment a gameObject which is in my scene to get its scripts and finally its methods. I can attach just the script but I cannot find the methods of it(They are public). I can't look into the prefab and at the same time at the game object so that I drag and attach into the onClick button. When I click one the other disappears. Any suggestions?
Answer by rohitkvasanth · Apr 23, 2019 at 10:30 AM
@anonrika It doesn't work that way. since you only need the scripts attached to the GameObject and not the Gameobject itself, create a singleton instance of that script you need to use and then you can access its public methods from any other script directly.
@rohitkvasanth Hey man thanx for the answer. Since I am new to unity can you explain what and how can I create a singleton instance?
@anonrika Like this. script A is the script outside. scriptB is the one attached to the prefab. create a singleton of script A and use that in script B.
Script A :
public ClassA : $$anonymous$$onoBehavior
{
// create a singleton instance
public static ClassA Instance;
private Awake()
{
if(!Instance)
Instance = this;
}
// public method
public void $$anonymous$$ethodA()
{
// code you need.
}
}
Script B:
public classB: $$anonymous$$onoBehavior
{
void $$anonymous$$ethodB()
{
// access the function from ClassA directly here.
ClassA.Instance.$$anonymous$$ethodA();
}
}
Answer by FullDefilate · Apr 23, 2019 at 12:05 PM
@anonrika Prefabs cannot contain references to scene objects , so this is why you are getting the reference removed.
What you can do though, is when you instantiate the object to your scene , find the object containing the function you want to call and pass it as a delegate on the OnClick event of your button like so:
TheButtonYouWant.onClick.AddListener(delegate{TheScriptYouWant.TheFunction({ function parameters}); });
Your answer
![](https://koobas.hobune.stream/wayback/20220612200039im_/https://answers.unity.com/themes/thub/images/avi.jpg)