- Home /
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.
This is fine for finding gameobjects which strangely enough I can get working. I'm trying to access a script thats on a gameobject so its similar and yet I still have no idea how to do it.
FindObjectOfType can be used from any script to find any other script type if it is in the scene.
How would one do this if the GameObject has yet to be instantiated? I'm trying something like this but I keep getting an error "Type "NameofScript" cannot be found"
public NameofScript other;
public GameObject go;
void Awake ()
{
GameObject go = Instantiate(Prefab, Vector3.zero, Quaternion.identity);
other = go.GetComponent<NameoftheScript>();
}
other.function();
Never$$anonymous$$d, it seems like I can't use a C# script to reference a JavaScript. @_@ Is that really too hard to do, Unity?
Answer by guitarninja · Apr 18, 2013 at 04:08 AM
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();
Answer by CrystalRain0329 · Apr 18, 2013 at 04:30 AM
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();
Your answer
Follow this Question
Related Questions
How do I call a function in another gameObject's script? 5 Answers
Call Functions Across Scripts, Null Object Error 1 Answer
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Referencing a Public GameObject from another script. 2 Answers
Accessing Variables within another gameobject's script 2 Answers