- Home /
Having troubble Calling a function from another script in a Prefab
void Awake () {
ScoreManager otherScript = GameObject.Find("scoreobject").GetComponent();
otherScript.AddEnemy();
}
scoreobject is the name of the Object with the ScoreManager script. this script is on a prefab so i cant just refrence the Scoremanager script thanks for any help
Answer by Esteem · Jan 22, 2020 at 07:57 PM
Instantiate the prefab instead of doing GameObject.Find, find only searches in the scene, not in the project.
GameObject.Find("scoreobject").GetComponent<.Score$$anonymous$$anager>();
it doesnt return anything because GameObject.Find does not look for the prefab in the project, it only searches the hierarchy of all active scenes and looks for an Instance of the prefab (meaning, it's searching for the object that gets created when you drag and drop your prefab to the scene) but since you don't have that in your scene, it cannot find anything.
You never interact with prefabs directly, you always interact with instances of prefabs that you create in your game using the drag and drop in the editor or by code:
public class Score$$anonymous$$anager : $$anonymous$$onoBehaviour {
public void AddEnemy() {
}
}
you slap the above on the prefab and then you create a new gameobject in the scene, put the below script on it, drag your prefab over the yourPrefabReference and that's it
public class Your$$anonymous$$onoBehaviour : $$anonymous$$onoBehaviour {
public Score$$anonymous$$anager yourPrefabReference;
private void Awake() {
Score$$anonymous$$anager otherScript = Instantiate(yourPrefabReference);
otherScript.AddEnemy();
}
}
Answer by carldevelopsforcoffee · Jan 22, 2020 at 11:13 PM
Possible Issues:
"scoreobject" should exist in the scene.
If it is in the project, try using
Resources.Load("scoreobject")
if you have this in your directory: Resources/scoreobject.prefabverify if Awake() is called. If the mono is loaded thru some other means, there are instances where monobehavior.Awake() isn't called. Try using Start() or OnEnable() if this happens.
Design Suggestions:
Setup your ScoreManager as a singleton.
public class ScoreManager : MonoBehaviour {
private static ScoreManager _instance;
public static ScoreManager GetInstance() {
// Can be called anywhere in the scene: ScoreManager.GetInstance().AddEnemy();
return _instance;
}
void Awake () {
// Note: Leave scoreobject on the scene so that this gets called.
_instance = this;
}
void OnDestroy () {
// This is automatically called when you exit your scene
_instance = null;
}
public void AddEnemy () {
// Do stuff here
}
}
public class SomeThing : MonoBehavior {
// Some other object in your scene (below scoreobject to let scoreobject.Awake() finish first)
void Awake () {
ScoreManager.GetInstance().AddEnemy();
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612221945im_/https://answers.unity.com/themes/thub/images/avi.jpg)