- Home /
assign ui panel to a prefab object ?
i have a ball object that keeps spawning , and when a player loses the game displays a game over panel , the problem here is that i couldn't assign the panel to the ball (ball prefab) , so how do i make it possible ? ps : the ball spawn endlessly , i tested the panel without making the ball a prefab and it worked just fine but the ball spawns just once and when i made the ball a prefab the panel wouldn't show when the player loses
Answer by WheresMommy · Dec 12, 2019 at 05:30 AM
You need to fire an event if the player loses. Then have the ui panel listen for that event and if triggered show the panel.
Edit: just to clarify, a prefab is loaded while the ui panel is on scene. Therefore you cant hold a reference to the panel if you instantiate the ball. You could findobjectpftype or do something but that would be some hacky way of doing it. I would go with a manager or a message broadcast to keep things object oriented and not stitched together.
i hope im not asking for a lot but can u provide an example ? and thank you
I'd go with a Game (or UI) $$anonymous$$anager, that holds a static instance of itself. Then you could either use delegates (thats another story) or just call that instance of the manager to call the game over function. Here is an untested code snippet
public class Game$$anonymous$$anager : $$anonymous$$onoBehaviour
{
public GameObject yourPanel;
public static Game$$anonymous$$anager instance;
private void Awake()
{
//Check if instance already exists
if (instance == null)
instance = this;
else if (instance != this)
Destroy(gameObject);
DontDestroyOnLoad(gameObject);
}
public void DoSomethingOnGameOver()
{
//Your script, like yourPanel.SetActive(true);
}
}
public class YourBallPrefabScript : $$anonymous$$onoBehaviour
{
//Use on destroy or oncollisionenter or whatever you prefer to run the code
public void YourFunction()
{
Game$$anonymous$$anager.instance.DoSomethingOnGameOver();
}
}
update :so far so good , although currently the panel is showing for just few seconds and then disappears , i'll try and see my way , but if u got any suggestions feel free to drop em , and thanks a bunch !
Answer by hameed-ullah-jan · Dec 12, 2019 at 10:10 AM
The easiest way would be to find the panel in the start function of your ball prefab, though it is not the best way there are many other ways to do it, but for you it will work. let me write some code snippet for you:
this script should be on your ball prefab "ball_script.cs", inside this script write this code:
public GameObject GameOverPanel;
void Start()
{
GameOverPanel = GameObject.Find("YourPanelName");
}
um it basically created a prefab of the panel , so im having same results , thank you
Your answer
Follow this Question
Related Questions
Tracking instantiated objects 1 Answer
Remove object assignment in runtime? 1 Answer
How can I assign a GameObject to a variable at runtime? 0 Answers