Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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 FlashX · Jan 08, 2017 at 12:08 AM · variablesfunctions

getting two results when i shouldnt be

hi guys,

so i have this problem:

i have two scripts, one is called Main.cs and the other GutterCheck.cs

im needing the following code frong Main.cs to add points to a variable in the in GutterCheck.cs

////// Main.cs

public class Main : MonoBehaviour {

 private GutterCheck myGutterCheckScript;   
     
 void Start(){
                  myGutterCheckScript = new GutterCheck();    
 }
 
 void Update () {
         if ( Input.GetMouseButtonDown (0)){ 
             RaycastHit hit;
             Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); 
             if ( Physics.Raycast (ray,out hit,100.0f)) {
                 if(hit.collider.tag == "enemy") { 
                     
                     print("---enemy hit");
 
                     myGutterCheckScript.updateScoreBoard(200);
                       
                 }
             }
         }
     }
 }
 

this is what i have in GutterCheck.cs...

/////GutterCheck//////

 public class GutterCheck : MonoBehaviour {
 
 
                      
 public int totalScore;
      
 
 
 public void updateScoreBoard(int amount){
    totalScore += amount;  //add the amount that was passed to the score
           print ("totalScore = " +totalScore);
      }
 
     
 }

My problem is that if i call the function from the Main.cs i get one lot of results and when i call the function from the GutterCheck i get an entirely new set of results

so for eg: when i call it from Main.cs the result will be 200, 400, 600 etc when i call it from GutterCheck.cs i get 2, 4, 6, 8 etc

its not actually calculating it together which makes me think that it sees it as another variable or something but how do i fix this?

Cheers,

Comment
Add comment · Show 3
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 allenallenallen · Jan 08, 2017 at 02:17 AM 0
Share

$$anonymous$$ay I ask how you are calling it from GutterCheck.cs if you instantiate one in $$anonymous$$ain.cs?

 void Start(){
     myGutterCheckScript = new GutterCheck();    
  }

Because each instantiation of a non-static class with non-static variables will be a separate new instance of the script. They won't be connected in a any way.

avatar image FlashX · Jan 08, 2017 at 02:45 AM 0
Share

Hi Allen,

Thanks for getting back,

I'm not sure that I have it set up correctly as I'm only learning how to do it.

the way I'm initialising it is like this:

 public GutterCheck myGutterCheckScript;       // Give access to another script 

then I'm setting it up:

     void Start(){
                  myGutterCheckScript = new GutterCheck();      
     }

then I'm calling it from the Update when the mouse button clicks an object that has a tag named "enemy"

    void Update () {
         if ( Input.Get$$anonymous$$ouseButtonDown (0)){ 
             RaycastHit hit;
             Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); 
             if ( Physics.Raycast (ray,out hit,100.0f)) {
                 if(hit.collider.tag == "enemy") { 
                     
                     print("---$$anonymous$$ole hit");
 
                     myGutterCheckScript.updateScoreBoard(200);
                       
                 }
             }
         }
     }


how can I write it that it can link to the same variable?

thanks :)

avatar image allenallenallen FlashX · Jan 08, 2017 at 03:16 AM 0
Share

There are a few ways to do this.

One way is to make the variable a static one:

 public static int totalScore;

This way, any instance of the script will have the same value for totalScore.

2 Replies

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by Bunny83 · Jan 09, 2017 at 05:16 AM

You made a big mistakes here. MonoBehaviour scripts can not be created with "new". Well you can, but it doesn't work properly as MonoBehaviour derived classes are components which need to be attached to a gameobject. You should actually receive a warning / error in the console about that.

Instead of creating a new instance of your "GutterCheck" script in Start, you should simply assign the object that has this script attached to to your "myGutterCheckScript" variable in the inspector. So make sure you remove that line completely:

 myGutterCheckScript = new GutterCheck(); 


ps: Even though Josh suggested using a static variable, it's in general not a good solution. Static things only exist once and will limit the usage of your script. static variables are "global state" which should be avoided if possible as it makes scripts and programs in general hard to debug / verify. It's better to use references between different components / classes. Those references can be set up either in the inspector at edit time or by using GameObject.Find + GetComponent at runtime.

Comment
Add comment · Show 1 · 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 FlashX · Jan 09, 2017 at 09:11 AM 0
Share

Cheers Bunny83 :)

avatar image
0

Answer by josh15 · Jan 08, 2017 at 08:28 AM

i have another idea that is it

  void Start(){
                
  }
  
  void Update () {
          if ( Input.GetMouseButtonDown (0)){ 
              RaycastHit hit;
              Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); 
              if ( Physics.Raycast (ray,out hit,100.0f)) {
                  if(hit.collider.tag == "enemy") { 
                      
                      print("---enemy hit");
  
                      GutterCheck .totalScore+=200;
                        
                  }
              }
          }
      }
  }


and the other script

  public class GutterCheck : MonoBehaviour {
  
  
                       
  public static int totalScore;
       
  
  
  void Update()
 {
  print ("totalScore = " +totalScore);
 }
  
      
  }
Comment
Add comment · Show 1 · 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 FlashX · Jan 08, 2017 at 04:10 AM 0
Share

oh dude! you're a legend! thank you so much that worked! argghhh! so many hours wasted banging my head and it all came down to one word ... "static" lol

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

62 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 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 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 avatar image avatar image

Related Questions

how to access variables in a function script attached to a clone 1 Answer

problems accessing variables and functions in another script 1 Answer

Referncing variables such as OnTriggerEnter(Collider other) thumb rule? 1 Answer

Can I pass a variable to a function to be assigned in c# 2 Answers

Referencing functions from other scripts as variables 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