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

Instantiate the prefab instead of doing GameObject.Find, find only searches in the scene, not in the project.

but this script is on the prefab

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.prefab
  • verify 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(); 
  } 
}