How do I enable/disable components in a prefab from another script?
I want to enable/disable components in my player prefab from another script. I have a UI Manager that has a public reference to my player controller script. There are a few bools to toggle the components on or off.
If I add my player prefab to the public reference spot from within the scene, it works perfectly fine. However, if I add my player prefab from the asset folder, it doesn't work at all.
This is a problem because the UI Manager won't work properly if I go into a different scene. If I'm referencing the player prefab from the prior scene, then the public script will state that the prefab "is missing." I want this to work by referencing the prefab in the asset folder.
Is there a way to do this? Let me know if you need more context.
Answer by goutham12 · Sep 27, 2019 at 06:20 AM
you might look into this topic. http://www.unitygeek.com/delegates-events-unity/
so basically your ui manager will rise an event and your player will reiceive the message. Am giving an example below. Write the below code in ui manager,
public delegate void m_Delegate();
public static m_Delegate OnAction;
void Update()
{
if(Input.GetKeyDown(KeyCode.Space)){
if(OnAction != null){
OnAction();
}
}
}
And in you playerScript
Void OnEnable(){
uiManager.OnAction += EventToRaise;
}
void OnDisable(){
uiManager.OnAction -= EventToRaise;
}
void EventToRaise(){
// do your stuff ----------------
}
Thanks a bunch, I've never heard of delegates before! I appreciate the help! Thank you!