Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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 Rick74 · Sep 05, 2013 at 03:01 PM · javascriptvariablegetcomponent

Issues with trying to change a variable in another script

This script has given me all sorts of problems, and here is the new one;

I'm trying to change a variable, and call a function from a script attached to an assigned GameObject variable.

Here's the script trying that's trying to call the change;

 #pragma strict
 
 var resourceValue:    int     =     25;
 
 var Countdown:        int     =     5;
 var visible:         float     =     0.50;
 var invisible:        float     =     0.50;
 var blinkFor:         float    =     5.0;
 var startState:     boolean =    true;
 
 var explosion:         GameObject;
 var mainGUI:        GameObject;
 
 function Start () 
 {
     animation.Play ();
     transform.position.z = -5;
     renderer.enabled = startState;
     yield WaitForSeconds(Countdown);
     
     var whenAreWeDone = Time.time + blinkFor;
     
     while (Time.time < whenAreWeDone)
     {
         if ( startState )
         {
             renderer.enabled = false;
             yield WaitForSeconds(invisible);
             renderer.enabled = true;
             yield WaitForSeconds(visible);
         } 
         else
         {
             renderer.enabled = true;
             yield WaitForSeconds(visible);
             renderer.enabled = false;
             yield WaitForSeconds(invisible);
         }
     }
     renderer.enabled = true;
     Destroy ( gameObject );
 }
 
 function Update ()
 {
     var hit     :RaycastHit;
     var ray     = Camera.main.ScreenPointToRay (Input.mousePosition);
     
     if ( Physics.Raycast ( ray, hit, 30 ))  
     {
           if ( hit.collider.gameObject.tag == "resource" && Input.GetMouseButtonDown (0))
            {
                AddValue ();
                Instantiate ( explosion, hit.collider.gameObject.transform.position, Quaternion.identity );
             Destroy (hit.collider.gameObject);
         }
        }
 }
 
 function AddValue ()
 {
     var test = mainGUI.GetComponent(LevelMaster).resourceCount;
     mainGUI.GetComponent(LevelMaster).resourceCount += resourceValue;

 //mainGUI.GetComponent(LevelMaster).UpdateHUD ();

     print ( test );
 }

And here's the script attached GameObject assigned to mainGUI;

 #pragma strict
 
 static var playerDamage:         float = 0;                //records the damage the player has taken
 
 var waveActive:                    boolean = true;            //toggles for controlling the wave
 var spawnEnemies:                 boolean = true;            //
 var bigSpawn:                    boolean = false;
 var firstWaveActive:             boolean = true;
 var secondWaveActive:             boolean = false;
 
 var healthCount:                 int = 10;                //players health count
 var resourceCount:                 int = 50;
 
 var waveText:                     UILabel;                //ui label 
 var resourceText:                 UILabel;
 
 
 var waveLevel:                    int = 0;                //current wave we are on
 var waveLength:                 float = 0;                //how long does the wave last before it stops
 var intermissionTime:             float = 15.0;            //how long to wait inbetween waves
 
 var enemyPrefabs:                 GameObject[];            //array that contains all the enemy types
 var enemyPrefabs02:                GameObject[];                
 var alienSpawnPoints:             Transform[];            //contains the spawn points
 var respawnMinBase:                float = 3.0;            //used to ramp up the amount of spawns
 var respawnMaxBase:             float = 10.0;            //
 private var respawnMin:         float = 3.0;            //
 private var respawnMax:         float = 10.0;            //
 private var waveEndTime:        float = 0.0;
 
 var difficulty:                 int = 0;
 var seconds:                     int = 0;
 var minutes:                    int = 0;
 
 function Start ()
 {
     
 }
 
 function Update () 
 {    
     Clock ();
     if (waveActive)
     {
         if ( Time.time >= waveEndTime )
         {
             spawnEnemies = false;
             FinishWave ();
             print ( "shutting off wave");
         }
     }
     if ( minutes >= 1 && firstWaveActive )
     {
         firstWaveActive = false;
         secondWaveActive = true;
         print ( "swapping over to second wave level");
         waveLength = 5;
     }
     if ( waveLevel == 09 && secondWaveActive )
     {
         secondWaveActive = false;
         bigSpawn = true;
         print ( "swapping over to big spawn");
         waveLength = 40;
         FinishWave ();
     }
     if ( minutes >= 4 )
     {
         difficulty = minutes - 2;
     }
 }
 
 function FinishWave ()
 {
     waveActive = false;    
     spawnEnemies = false;
     var i: int;    
                                                     
     if ( firstWaveActive )
     {
         i = Random.Range (20, 30);
         print ("under 1 minute, waiting for "+i);
         yield WaitForSeconds (i);                                        //waits for the the intermission time to pass
         SetNextWave ();                                                    //sets the next wave command
         StartNewWave ();            
     }
     if ( secondWaveActive )
     {
         i = Random.Range (12, 18);
         print ("over 1 minute, waiting for "+i);
         yield WaitForSeconds (i);                                        //waits for the the intermission time to pass
         SetNextWave ();                                                    //sets the next wave command
         StartNewWave ();        
     }
     if ( bigSpawn )
     {
         print ("HERE THEY COME!!!");
         yield WaitForSeconds (10);
         SetNextWave ();
         StartNewWave ();
     }
 }
 
 function SetNextWave ()                                                //prepares the values for the next wave (how many enemies will be spawn)
 {
     waveLevel ++;                                                       //ups the wave level
 }
 
 function StartNewWave ()
 {
     UpdateHUD ();                                                    //updates the gui
     NewSpawnEnemy ();                                                //spawns new enemy
     waveActive = true;                                                //sets the toggle to spawn enemies
     spawnEnemies = true;
     waveEndTime = Time.time + waveLength;
 }
 
 function UpdateHUD ()
 {
     waveText.text = "Wave: " +waveLevel;                            //updates the current waveLevel to the wave GUI
     resourceText.text = "Resources: " +resourceCount;                //updates the current healthLevel to the health GUI
 }
 
 function NewSpawnEnemy ()
 {
     if ( minutes <= 1 && firstWaveActive && !bigSpawn )
     {
         FirstLevelSpawn ();
         print ("first level spawn happening");
     }
     if ( minutes >= 1 && !bigSpawn && secondWaveActive && !firstWaveActive )
     {
         SecondLevelSpawn ();
         print ("second spawn happening");
     }
     if ( bigSpawn && !secondWaveActive )
     {
         BigSpawn ();
         print ("big spawn happening");
     }
 }
 
 function FirstLevelSpawn ()
 {
     var i = difficulty;
     for (; i >= 0; i--)
     {
         var enemyChoice = Random.Range (0, enemyPrefabs.Length);
         var spawnChoice : int;    
         spawnChoice = Random.Range (0, alienSpawnPoints.Length);
         Instantiate (enemyPrefabs[enemyChoice], alienSpawnPoints[spawnChoice].position, alienSpawnPoints[spawnChoice].rotation);
         print ( "1 enemy spawned");
     }
 }    
 
 function SecondLevelSpawn ()
 {    
     var i = difficulty;
     for (; i >= 0; i--)
     {
         var enemyChoice = Random.Range (0, enemyPrefabs02.Length);
         var spawnChoice : int;    
         if ( enemyChoice == 1 )
         {
             var a = 1;
             for (; a >= 0; a--)
             {
                 spawnChoice = Random.Range (0, alienSpawnPoints.Length);
                 Instantiate (enemyPrefabs02[enemyChoice], alienSpawnPoints[spawnChoice].position, alienSpawnPoints[spawnChoice].rotation);
             }
         }
         if ( enemyChoice == 0 )
         {
             spawnChoice = Random.Range (0, alienSpawnPoints.Length);
             Instantiate (enemyPrefabs02[enemyChoice], alienSpawnPoints[spawnChoice].position, alienSpawnPoints[spawnChoice].rotation);
         }
     }
     print ( "second level spawn finished" );
 }
 
 function BigSpawn ()
 {
     print ("Big Spawn!");
     var i = 3;
     for (; i >= 0; i--)
     {
         var enemyChoice = Random.Range (0, enemyPrefabs02.Length);
         var spawnChoice : int;    
         if ( enemyChoice == 1 )
         {
             var a = 1;
             for (; a >= 0; a--)
             {
                 spawnChoice = Random.Range (0, alienSpawnPoints.Length);
                 Instantiate (enemyPrefabs02[enemyChoice], alienSpawnPoints[spawnChoice].position, alienSpawnPoints[spawnChoice].rotation);
             }
         }
         if ( enemyChoice == 0 )
         {
             spawnChoice = Random.Range (0, alienSpawnPoints.Length);
             Instantiate (enemyPrefabs02[enemyChoice], alienSpawnPoints[spawnChoice].position, alienSpawnPoints[spawnChoice].rotation);
         }
         print ( "big spawn loop "+i);
     }
     bigSpawn = false;
     secondWaveActive = true;
     waveLength = 5;
     print ("big spawn finished");
 }
 
 function Clock ()
 {
     seconds = Time.time % 60;
     minutes = Time.time / 60;
 }

So while I look at the value of "resource Count" while the game is going, it doesn't go up at all. It stays at 50 in the inspector. What I find weird is, if I call that print command "test" to tell me what the current value of "recource Count is", I get something else. And while most of the time, it's adding a straight "25" to the value, I'm finding that sometimes it's adding a ton more. 75-100 in some cases.

As you can see, I've also commented out trying to call the function from the script "LevelMaster", It was giving me a NullReferenceException: Object reference not set to an instance of an object LevelMaster.UpdateHUD () (at Assets/Scripts/LevelMaster.js:124) Which drives me nuts, because that script is clearly attached to the GameObject assigned to mainGUI in the inspector.

Very confused here. :(

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

1 Reply

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

Answer by clunk47 · Sep 05, 2013 at 04:12 PM

I'll just skip over all this code and give an example in JS on how to access a variable from another script using GetComponent. Lets say you have a script with a GameObject variable assigned, and that GameObject has another script attached called "ScriptToAccess". In this "ScriptToAccess" class, you'd have a variable called "score". Let's say as a test, you want to hit 'E' to add score on each keypress:

 #pragma strict
 
 var go : GameObject;
 
 function Update()
 {
     if(Input.GetKeyDown(KeyCode.E))
     {
         if(go.GetComponent(ScriptToAccess))
         {
             go.GetComponent(ScriptToAccess).score += 100;
         }
     }
 }





Comment
Add comment · Show 11 · 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 meat5000 ♦ · Sep 05, 2013 at 04:17 PM 2
Share

He's trying to call a function so

 go.GetComponent(ScriptToAccess).callingFunction();
avatar image clunk47 · Sep 05, 2013 at 04:33 PM 1
Share

The problem with the variable not being reset sounds like you need to CLONE your prefab.

 //Assign your prefab to this in inspector.
 var lm : GameObject;
 
 //Use instantiation in any function, this is just an example method.
 function ClonePrefab()
 {
 //Clone lm GameObject and bring in a new instance to your scene, so your prefab will not be affected.
     var lmClone = Instantiate(lm, transform.position, Quaternion.identity);
 }
avatar image clunk47 · Sep 05, 2013 at 04:42 PM 1
Share

I noticed the underscore too, but it doesn't make a difference, underscores are fine for object names.

avatar image Rick74 · Sep 05, 2013 at 04:42 PM 2
Share

The _ just keeps the prefab at the top of the Hierarchy, and easy to find. It was just a trick I saw once in a tutorial.

avatar image clunk47 · Sep 05, 2013 at 05:28 PM 1
Share

static is just kind of sloppy if you're using it on GameObjects as far as I know, you have to reset things manually in some conditions. Usually the only reason I use static is for a script not attached to anything in the game, and use scripts attached to gameObjects to access the static class. Another reason to use static would be for Editor scripts in Unity. If you choose to use static, there can be only ONE instance of the variable or class.

Show more comments

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

18 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

Related Questions

Accessing a variable that has a unique class 2 Answers

How could you access a script of varying name? 5 Answers

C# line into Javascript help 1 Answer

Access variable from multiple scripts 2 Answers

Need to use 2 different language scripts. 1 Answer


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