How to run function in another script with prefabs? C#

I have gameObject A with script A, how do I then call a function in gameobject b’s script b without using the “direct reference” made in the Editor by dragging the gameobject with scriptb onto the “other” variable?

Reason being is that script A’s gameobject needs to be a prefab as it will be instantiated and when needed with run a function in scriptb which is my gamecontroller


using UnityEngine;
public class ScriptA : MonoBehaviour
{
  public ScriptB other;
 
  void Update()
  {
    other.DoSomething();
  }
}

using UnityEngine;
public class ScriptB : MonoBehaviour
{
  public void DoSomething()
  {
     Debug.Log("Hi there");
  }
}

I’ve tried all sorts such as the below but just can’t get my head around it.

ScriptB otherScript = GetComponent<ScriptB>();
otherScript.DoSomething();

ScriptB other = (ScriptB) go.GetComponent(typeof(ScriptB));
other.DoSomething();

If I have scriptA and scriptb on the same gameobject it just works but putting them on different gameobjects only works using the “direct reference” made in the Editor.

Brilliant I got it working.


public NameoftheScript other;
public GameObject SpawnZone;

void Awake ()
	{
		// Setting up the reference.
		GameObject SpawnZone = GameObject.Find("NameoftheGameObject"); 	
		other = SpawnZone.GetComponent<NameoftheScript >(); 				
    				
	}

//just use the below where ever to activate
other.NameoftheFunction();

If you can get GameObject.Find working, then you should be able to combine it with your GetComponent example to get what you want:

ScriptB otherScript = GameObject.Find(“Name of GameObject with ScriptB you want”).GetComponent();
otherScript.DoSomething();