- Home /
Calling a from another script c#
I want to run a function from another script. the scripts are on separate objects dunno if that matters
public class Chop_wood : MonoBehaviour { public int inventory = 0; void OnTriggerEnter (Collider col) { Debug.Log ("at the tree"); //Chop (); } public void Chop() { inventory++; Debug.Log ("i am chopping the wood"); } void Update () { } }
And here is the other script, im trying to run the Chop() function but it tells me Object reference not set to an instance of an object chopped.OnTriggerEnter (UnityEngine.Collider col) (at Assets/chopped.cs:20)
public class chopped : MonoBehaviour {
public Chop_wood chopWood;
void Start()
{
chopWood = GetComponent<Chop_wood> ();
}
void OnTriggerEnter (Collider col)
{
if (col.collider.name == "Pirate_Chopper")
{
Debug.Log ("in the trigger");
chopWood.Chop();
}
}
void OnTriggerStay (Collider other)
{
}
}
the funny thing is it worked once and that time it still gave me the error, whats wrong?
Answer by giano574 · Oct 01, 2014 at 09:38 PM
It doesn't work because you are trying to get the Chop_wood component from the same GameObject as your second script is attached to.
GetComponent<Chop_wood>();
is the same as
this.GetComponent<Chop_wood>();
I assume the Chop_wood script is attached to another GameObject. The easiest way then, is to assign the GameObject with the Chop_wood script to the chopWood variable from the editor. You will notice that when selecting the GameObject with the chopped script in the hierarchy view that the chopWood variable is visible in the inspector. You can then drag the GameObject with the Chop_wood script to this variable. The editor will automatically take the correct script from the GameObject.
Then delete this line in the Start method:
chopWood = GetComponent<Chop_wood>();
Answer by psycocrusher · Oct 01, 2014 at 11:51 PM
Add the name of your gameobject in the parenthesis.The one that has the ChopWood function.
void Start(){
chopWood = GameObject.Find("").GetComponent<Chop_wood>();
}
Your answer
Follow this Question
Related Questions
Calling a function from a different script on the same object 1 Answer
How to use UnityAdsVideoCompleted(); 0 Answers
Is there any way to check which method called a certain other method? 1 Answer
Need help with If/else statement. 1 Answer
How to reference another script and call a function in C# ? 2 Answers