Calling function from other scripts c#

how would one go about calling a function from one script from another? in c#
eg
scriptB calls function test() from scriptA

if it make a difference the objects the the scripts are on is know before execution

4 Likes

Typically you would acquire the component using GetComponent(), and then call the function. e.g.:

myObject.GetComponent<MyScript>().MyFunction();
34 Likes

could you explain a little more

im not entirely sure how that works, what is game object supposed to be? the name of the object the script is on ? and should be the name of the script with the function so .

i tryed using the code from the unity reference

ScriptName sn = gameObject.GetComponent<ScriptName>()
sn.DoSomething();

but get the error
The type or namespace name `ScriptName’ could not be found. Are you missing a using directive or an assembly reference?

8 Likes

[link broken]

2 Likes

Right on both counts.

Well, why would you expect that to work? :slight_smile: The name of your particular script doesn’t appear anywhere in that code, so how would it know what component to look for? (Hint: it’s just example code - ‘ScriptName’ is a placeholder for whatever component type you’re interested in.)

5 Likes

Just upgraed to 4.3; not sure if that is a variable in this equation. Even with a switch of names, it still cannot find the script reference. On top of that, I also cannot access the containing object with this script. Additional annotation is required on this answer, hands down.

So the hard part is getting a handle to your other script. If the objects already exist in the game scene, then you can drag the object with ScriptA onto the inspector for ScriptB.

using UnityEngine;

public class ScriptB {
  // Assign by dragging the GameObject with ScriptA into the inspector before running the game.
  public ScriptA m_someOtherScriptOnAnotherGameObject;

  void Start() {
    m_someOtherScriptOnAnotherGameObject.Test();
  }
}

There are tons of ways to get handles to other scripts. Another example:

void Start() {
  m_someOtherScriptOnAnotherGameObject = GameObject.FindObjectOfType(typeof(ScriptA)) as ScriptA;
  m_someOtherScriptOnAnotherGameObject.Test();
}
32 Likes

Garth, you sir, and this is not idle compliment, are a genius.

To anyone searching henceforth. It would seem in my code as it is now, that one must use Garth’s syntax of accessing a brethren method to achieve any degree of success. Any deviation from GameObject.FindObjectOfType(typeof(scriptName) as scriptName; does now not seem to work, and Garth’s example above rings true.

Once again, thank you, and I will be referencing another thread to this location considering the lack of response of both extensive searching and thread response.

9 Likes

Thanks for the kind words! Glad to help =)

1 Like

Here’s that thread, for anyone interested: http://forum.unity3d.com/threads/212411-The-definitive-answer-to-C-cross-script-communication?p=1427010&viewfull=1#post1427010

Edit: I’d suggest checking out that link because while the above is definitely one option it’s only useful in certain cases. Other cases are covered by other options which are discussed in the linked thread.

1 Like

Very well

Thank you so much for this. I couldn’t wrap my brain around what I was doing wrong, and honestly, I still don’t FULLY understand how this works. But one thing is for sure, IT WORKS!!! I’m going to study it and use the docs to really dissect how this works.

I really appreciate it.

using UnityEngine;

public class ScriptA {

   public class ScriptAPartToUse {
      void ScriptAFunction(){
         //some code here
      }
   }

}
using UnityEngine;

public class ScriptB {
   ScriptAPartToUse Name = new ScriptAPartToUse();
   
   void Start() {
      Name.ScriptAFunction();
   }

}

I think it would be better. This example does not require dragging scripts anywhere. This example is a simplified version.

http://unity3d.com/learn/tutorials/modules/intermediate/scripting/properties

Type of all scripts in Unity3d - MonoScript. This code looks strange.

11 Likes

posted in the wrong damn forum xD

Sorry.

1 Like

Would it be easier to simply use the SendMessage command? In this example, I will use the Damage Function of another object.

using UnityEngine;
using System.Collections;

public class findObjectControls : MonoBehaviour
    {

    public Transform activateDamage;

    // Update is called once per frame
    void OnCollisionEnter(Collision other)
        {
        if (other.transform.tag == "Player")
            {
            playerTransform.SendMessage("DamagePlayer", 100f, SendMessageOptions.DontRequireReceiver);
            }
        }
    }

Is there something this doesn’t do? Or is there a benefit of the other posibilities?

2 Likes

Yep, exactly what I needed. Short and to the point. Thanks!

1 Like

SendMessage is limited to passing only a single parameter. If you need to pass more info between scripts on different objects you can achieve the same thing like this…

Public GameObject objectToAccess;
// drag the object you're calling a method on into the inspector, or alternatively use GameObject.Find to get a handle on it

ScriptName scriptToAccess = objectToAccess.GetComponent<ScriptName>();
// get the script on the object (make sure the script is a public class)      

scriptToAccess.YourMethodName(your parameters etc);
// calls the method in the script on the other object.
7 Likes

For me it only tels me that m_someOtherScriptOnAnotherGameObject does not exist in the current context, If it is suposed to be a variable, what kind of variable is it?

1 Like

in the example you are replying to it is of type “ScriptA”, that error is basically saying “ScriptA” doesn’t exist in your project. Replace all instances of “ScriptA” in that example with the type of your specific scriptname. i.e. if you are trying to access “GameManager” script “ScriptA” is replaced with “GameManager”. The variable name is mostly irrelevant to the mechanical function, but using something appropriately descriptive would be good

2 Likes

Try

ScriptToAccess=ObjectName.GetComponent("ScriptName") as MonoBehaviour;

Where ObjectName is the name of the object that contains the script you are accessing from elsewhere.

As LeftyRighty says, make sure “ScriptName” is the same as the name of the script you need.

See this similar post:

http://answers.unity3d.com/answers/669527/view.html

1 Like