Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Chricken · Dec 19, 2013 at 07:24 AM · c#functionc

Calling a function in another script

Hi, I am sorry for my stupid first question. I am very noobish to unity-scripting. Before Unity, I have only programmed in Flash and Javascript, which works mainly with one single file. Now, here are so many files, which confuses me a bit.

I simply have the question, how to call a function from an other class. Meaning: I have one script, which contains a function, that I want to call from different scripts. Lets say, this is the class with the function I would like to call:

 using UnityEngine;
  using System.Collections;
  public class patsch : MonoBehaviour {
      public void laerm(){
          print("Lärm");
      }
  }

And I have an other script like this (attached to a rigidbody):

using UnityEngine; using System.Collections;

public class faden : MonoBehaviour {

  void OnMouseDown() {
      float rnd = Random.Range(-50,50);
        rigidbody.AddForce(0,0,100);
        rigidbody.AddTorque(0f,rnd,0f);
        // I would love to call my function on this place
  } }

How do I do this?

Regards Chricken

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

3 Replies

· Add your reply
  • Sort: 
avatar image
2

Answer by fafase · Dec 19, 2013 at 08:00 AM

In order to call a method from one class to another class, the way may depend on the purpose and use.

So first off, do not fall in the trap of "Make it static".

If your method acts on the object then no static, if the method work more as general feature of a class then yes you could go for static.

Take the Vector3 class,

 Vector3 vec= new Vector3(10,10,10);
 vec.Normalize();

is a method that modify the actual vector object, so this one should be a instance method.

 Vector3 vecA = new Vector3(10,10,0);
 Vector3 vecB = new Vector3(20,20,0);
 float dot = Vector3.Dot(vecA,vecB);

in this case vecA and vecB are used but not modified so a static method is defined. Actually, you could make dot an instance method that you used:

 Vector3 vecA = new Vector3(10,10,0);
 Vector3 vecB = new Vector3(20,20,0);
 float dot = vecA.Dot(vecB);

but it seems less intuitive.

Also, static methods do not allow to use instance members so if your method should use any member of the object, bam, you cannot or you have to pass them as argument...

Now considering you have this:

 public class ClassA:MonoBehaviour{
    int a;
    public void PrintA(){
        print(a);
    }
 }

See, a is an instance member so if PrintA was static, it could not see a.

Now other class:

 public class ClassB:MonoBehaviour{
     public void DoSmgWithClassAMethod()
     {
         GetComponent<ClassA>().PrintA();
     }
 }

And GetComponent is how you access members from other classes. There are loads of examples so I won't go any further into this since you can find a lot of them using google.

http://unitygems.com/script-interaction1/

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
1

Answer by hirenkacha · Dec 19, 2013 at 07:28 AM

For Calling a function of one class from another you should make that function as static. And you can call that static methods from the another classes. If your method contains non static variables, you can create a static Instance.

Class Patsch:

 using UnityEngine; 
 using System.Collections;
 
 public class patsch : MonoBehaviour 
 {
    public static patsch Instance;

    void Start ()
    {
      Instance=this;
    }

    public void laerm()  //<---- public method
    {
         print("Lärm");
    }
 }
 

And the another class is

 using UnityEngine; 
 using System.Collections;
 
 public class faden : MonoBehaviour 
 {
         void OnMouseDown() 
         {
            float rnd = Random.Range(-50,50);
            rigidbody.AddForce(0,0,100);
            rigidbody.AddTorque(0f,rnd,0f);
          
            //Call that function
            patsch.Instance.laerm();   //<------ Call method
         }
 }
 

Also go through the naming convensions for c#

Comment
Add comment · Show 6 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image hirenkacha · Dec 19, 2013 at 08:12 AM 0
Share

The problem you talking about declaring static method can be solved using static Instance as above. I use this ins$$anonymous$$d of GetComponent() if I dont have the scripts attached to same object. and also if I dont have to look for the object.

avatar image fafase · Dec 19, 2013 at 08:14 AM 0
Share

You edited and it is still wrong. Instance is this, yep, if you have many objects, how do you know which is Instance? You cannot.

  "Also go through the na$$anonymous$$g convensions for c#"

good advice, you should read on then.

avatar image hirenkacha · Dec 19, 2013 at 08:21 AM 0
Share

this can happen with your case too. Which object to select while using GetComponet(); You cant say this is wrong. But you have different method too.

avatar image fafase · Dec 19, 2013 at 10:14 AM 0
Share

This would depend on what trigger the need to call. If you do that because of collision (most likely if you have a lot of the same object), then the collision method gives you a reference to the other object. If you know in advance what object it will be, then you can use GameObject.Find("ObjectName"). Or you can simply drag and drop in the Inspector. Last case it is already on the same object.

So all in all, I will always get the object I need and the script I target, you will always get the latest created object and the script on it.

Your way is not a different method, it is a wrong method. Static is to be used when appropriate, this is not a case for it.

avatar image hirenkacha · Dec 19, 2013 at 10:29 AM 0
Share

The question doesn't indicate such case of trigger or anything. It says "I simply have the question, how to call a function from an other class?" And his background was flash and javascript thats why I gave this.

Show more comments
avatar image
0

Answer by Stephanie-The-Viking · Jun 03, 2014 at 12:33 AM

If you have a method in ClassA thus:


public Class ClassA : MonoBehaviour

void PrintName() { Debug.Log("YourNameHere") }


In order to activate PrintName() from ClassB, you can simply have this:

public Class ClassB : MonoBehaviour

public GameObject ClassAObject;

void Start() { ClassAObject.SendMessage ("PrintName"); }

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

20 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

C# Call a funtion in many scripts 1 Answer

Lower player's health from separate script. 2 Answers

How do I use a function in a class more than once? 4 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges