Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How to multiply by a GUIText.Text

Discussion in 'Scripting' started by suspensemusic, Jan 4, 2014.

  1. suspensemusic

    suspensemusic

    Joined:
    Dec 4, 2013
    Posts:
    41
    I need to multiply an int by a string..

    Code (csharp):
    1.     public int scoreAdded;
    2.  
    3.     public GUIText Multiplier;
    4.  
    5.     void OnCollisionEnter(){
    6.  
    7.         int multiplier = Multiplier.text; // This is the issue
    8.  
    9.         Score.score += (scoreAdded * multiplier);
    10.         Score.progressMulti++;
    11.         for(int i = 0; i < amount; i++)
    I know why it doesn't work but I can't seem to find a way to do this.
     
  2. MDragon

    MDragon

    Joined:
    Dec 26, 2013
    Posts:
    329
    Not sure if that's the best design choice (ie why is the Multiplier a GUIText and can't be anything else?), but a quick Google search for C# string to int...
    http://msdn.microsoft.com/en-us/library/bb397679.aspx

    An example tested right now in Unity...
    Code (csharp):
    1.         string testS = "10";
    2.         int testI = System.Convert.ToInt32 (testS);
    3.         print (testI);
    Edit: Sorry if I didn't directly answer your question, but what I meant by the first sentence is I'm not sure why you would necessarily need to multiply the GUIText directly/as-is/etc. Sort of burnt out tonight after trying to figure something out, so I couldn't wrap my mind around your code properly. However, converting the text to int should solve the issue. HOWEVER, I haven't tested yet if GUIText.Text is specifically a string type, and I'll await a reply to see if I should try to rethink these short solutions :)
     
    Last edited: Jan 4, 2014
  3. jgodfrey

    jgodfrey

    Joined:
    Nov 14, 2009
    Posts:
    564
    To reinforce what MDragon said above...

    While you definitely *can* convert a string to an integer (provided the string value can be converted), that's probably not the best choice. Presumably, your GUIText item is just a *visual* representation of some internal variable's value. By your description, that variable is probably already an integer and is just being displayed in a GUIText item. So, you should be using the actual integer variable for your multiplication, not the string representation of that variable held in the GUIText item.

    Jeff
     
  4. suspensemusic

    suspensemusic

    Joined:
    Dec 4, 2013
    Posts:
    41
    Thank you.. I took your advice on the bad design and decided to call the int that I was casting into the GUI. I just needed to move it into the Start Function instead of the Collision. That was my initial problem.