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 /
  • Help Room /
avatar image
0
Question by Kilner · Jun 28, 2018 at 05:44 AM · 3deditor-scriptingbeginnerglobal variable

Unwanted behavior when manipulating a public integer from a different script: How can it be fixed?

Script Info:

  • BaseUpgrades script is on a cube thats in the scene.

  • Second script is on a TextMeshPro object which is not in the scene by default but is instantiated by the enemy when the enemy dies.

  • Third script is located on another TextMeshPro object which is parented to a canvas.

  • The Second and BaseUpgrades scripts have the object they are included on in the asset list (would you call them archetypes?).


Description: In the Second Script When an enemy dies it displays text showing its base money reward times a randomly determined multiplier. This value is then stored in the totEarned variable. This value is supposed be added onto the total money in the BaseUpgrades script when the text object fades to an alpha value of 0. However, during runtime the displayed integer value does not change when an enemy is killed. When i stop the game runtime (by toggling off the play button) and select the cube object containing the BaseUpgrades component, its public money value displays the value as if it was working correctly (IOW: enemies added their money drop to the money variable).

As shown below (Money val is initially set to 100):

alt text


The BaseUpgrades script:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class BaseUpgrades : MonoBehaviour {
     public int money;
     public int maxTurretPlaced = 3;
 
     void Start () {
         money = 100;
     }
     
     // Update is called once per frame
     //void Update () {
     //
     //}
 
     public void AddMoney(int i){
         money += i;
     }
 }
 

Below will be the two scripts that manipulate the money variable in the BaseUpgrades script shown above

Second Script:

 sing System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class EnemyDeathText : MonoBehaviour {
 
     public Color myColor; 
     public float duration = 1.5f;
     public int BaseMoneyOnDeath = 50;
     public  GameObject moneyStorage;
     public BaseUpgrades moneyScript;
     float alpha;
     bool colorWasSet = false;
     float yPos;
     int totEarned;
     private TMPro.TextMeshPro textComp;
     bool dying = false;
 
 
     void Start () {
         textComp = this.GetComponent<TMPro.TextMeshPro>();
         textComp.color = myColor;
         alpha = 1;
         yPos = 1;
         colorWasSet = true;
 
         moneyScript = moneyStorage.GetComponent<BaseUpgrades>();
 
         textComp.text = MoneyToString();
         //Debug.Log(textComp.text);
     }
 
     string MoneyToString()
     {
         double randNum = NextGaussian();
         randNum = 0.5*randNum+1;
         randNum = ((double)Mathf.Round((float)randNum*10))/10;
 
         if(randNum < 0)
             randNum *= -1;
 
         textComp.fontSize = (float)randNum*5+20;
 
         totEarned = Mathf.RoundToInt((float)randNum*BaseMoneyOnDeath);
 
         return BaseMoneyOnDeath + "X" + randNum;
     }
 
     public static float NextGaussian() {
         float v1, v2, s;
         do {
             v1 = 2.0f * Random.Range(0f,1f) - 1.0f;
             v2 = 2.0f * Random.Range(0f,1f) - 1.0f;
             s = v1 * v1 + v2 * v2;
         } while (s >= 1.0f || s == 0f);
 
         s = Mathf.Sqrt((-2.0f * Mathf.Log(s)) / s);
     
         return v1 * s;
     }
     
     // Update is called once per frame
     void Update () {
         if(!colorWasSet)
             return;
         alpha -= Time.deltaTime / duration;
         yPos+=Time.deltaTime;
         transform.position = new Vector3(transform.position.x,yPos,transform.position.z);
 
         textComp.color = new Color(textComp.color.r,
                                     textComp.color.g,
                                     textComp.color.b,
                                     alpha);
         if(alpha <= 0){
           ////////////////////////////////////////////////////////////
           //////    \/ Mentioned attempt at changing var\/      //////
           ///////////////////////////////////////////////////////////
             moneyScript.AddMoney(totEarned);
             Destroy (gameObject);
         }
     }
 }

ThirdScript:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class DisplayText : MonoBehaviour {
 
     public GameObject WhatToTrack;
     public bool isBar = false;
     private TMPro.TextMeshPro m_Text;
     private TMPro.TextContainer m_TextContainer;
     private RectTransform Scale;
     private Health obj;
     private BaseUpgrades obj2;
 
     void Start () {
         if(WhatToTrack.GetComponent("Health") != null){
             obj = (Health)WhatToTrack.GetComponent("Health");
         }
         else if(WhatToTrack.GetComponent("BaseUpgrades") != null){
             obj2 = (BaseUpgrades)WhatToTrack.GetComponent("BaseUpgrades");
         }
         if(!isBar){
             m_Text = GetComponent<TMPro.TextMeshPro>() ?? gameObject.AddComponent<TMPro.TextMeshPro>();
                m_TextContainer = GetComponent<TMPro.TextContainer>();
         }
         else if(isBar){
             Scale = this.GetComponent<RectTransform>();
         }
     }
     public void setMoneyVal(){
         m_Text.text = "" + obj2.money;
     }
     
     void Update () {
         if(m_Text != null){
             if(obj != null){
                 m_Text.text = "" + obj.health;
             }else{ 
                 setMoneyVal();
             }
         }// && obj.health != prevHealth
         else if(isBar){
              Scale.localScale = new Vector3(Mathf.Lerp(Scale.localScale.x, obj.health*5, Time.deltaTime * 10f), 1f, 1f);
         }
     }
 }


capture.jpg (56.1 kB)
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
0
Best Answer

Answer by Kilner · Jul 17, 2018 at 12:33 AM

The problem revolved around my use of pointers to the game object assets. As they were created at a different time i had to use code that found the object in the level instead of manually linking the object via a property.

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

174 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 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 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

Going back to MainMenu from other level. (Problem) 0 Answers

Followed Brackey's 1st person movement tutorial but the jump mechanic won't work and sometimes neither will the gravity 0 Answers

Loosing references when going in playmode 0 Answers

How to make a sound 3D? 1 Answer

Sphere is not using OnCollisionEnter/OnTriggerEnter/OnCollisionStay/OnTriggerStay functions 0 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