Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Can't convert string to int

Discussion in 'Scripting' started by mate_veres, Mar 3, 2020.

  1. mate_veres

    mate_veres

    Joined:
    Oct 19, 2019
    Posts:
    72
    Good Evening!

    This is probably a very easy question, but I just can't find out the solution.

    So I want to have a list which stores a set of points position and I would currently arranging the points by their name (I know it isn't so elegant if you know a better method, please let me know ). Whenever a point has duplicated its name changes to name + (instance number). I want to index the objects by their instance number.

    I tried this:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using System;
    5.  
    6. public class Vertices : MonoBehaviour
    7. {
    8.    
    9.     public static List<Vector2> terrainWayPoints = new List<Vector2>();
    10.     public static int placement = 0;
    11.     private int ownPlacement;
    12.     string instanceString ;
    13.  
    14.  
    15.     private void Start()
    16.     {
    17.        
    18.        
    19.         if(name == "TerrainPoint")
    20.         {
    21.             placement = 0;
    22.         }
    23.         else
    24.         {
    25.            
    26.             instanceString = name[13].ToString();
    27.             terrainWayPoints[int.Parse(instanceString)] = transform.position ;
    28.            
    29.          
    30.          
    31.            
    32.            
    33.         }
    But I got back an error at the int.Parse() that my string isn't in the right format.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,945
    TheDevloper likes this.
  3. mate_veres

    mate_veres

    Joined:
    Oct 19, 2019
    Posts:
    72
  4. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    Output the value of instanceString using Debug.Log before you use int.Parse. If int.Parse fails it means what is in instanceString can't be converted to an int. So I'm guessing that name[13].ToString() isn't resulting in the string you expect it to.
     
  5. mate_veres

    mate_veres

    Joined:
    Oct 19, 2019
    Posts:
    72
    Hello that was the problem I was just so stupid for some reason that I didn't see it. SHAME.
     
  6. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,748
    Before you do the parse, output the value of instanceString. What does it contain? You may be off by 1 on your indexing or something, resulting in something that's not a number.

    Even if you fix this you'll have another problem, which is that you can't set list items like you are. Your List has a length of 0 (no items in it), so even if you correctly parse the number, you'll be trying to set index 5 of a 0-length list, which will cause another error.

    If you can avoid it (and you totally can), best to avoid parsing strings at all, particularly human-created strings. You could, as one example, make an int on your script that is the index. If you want this to be reflected in the GameObject's name, go the other direction: make the name a result of the int, not the other way around. You could do this in the editor with OnValidate, which is executed anytime values are changed in the Inspector:
    Code (csharp):
    1. public int myIndex = 0;
    2.  
    3. void OnValidate() {
    4. gameObject.name = "My thing "+myIndex;
    5. }
    As for the second problem, try this: Rather than setting a specific index of the list to your position, have each object add itself to a SortedList<int, Vector3>. This is not only going to be more reliable, but also faster and more extensible than trying to weedle an int out of your GameObject's name.

    And there's one other thing, which is an issue with static variables: in the editor, they persist between runs (basically until you recompile scripts). That means that your list will have the old points when you re-enter play mode. Let's solve this the easy way and initialize the list in Awake(), then add items in Start().
    Code (csharp):
    1. public static SortedList<int, Vector3> terrainWayPoints;
    2.  
    3. public int myIndex = 0;
    4. void Awake() {
    5. terrainWayPoints = new SortedList<int, Vector3>();
    6. }
    7.  
    8. void Start() {
    9. terrainWayPoints.Add(myIndex, transform.position);
    10. }
     
  7. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,945
    This should always be the First Step(tm) when diagnosing a data problem.

    And all problems are just data problems. :)
     
    Joe-Censored likes this.
  8. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    Don't worry about it. Sometimes when working on a problem you get tunnel vision, ignoring possible issues which don't conform to assumptions. One thing I sometimes do is just walk away from the problem for a bit, switch to something else, and come back later with fresh eyes.

    But the first step I do when troubleshooting this kind of thing is just Debug.Log almost everything involved. If you couldn't figure it out before, you're usually in for a surprise when you check the console. So many times I've done that and yelled out loud "how the %$@* is that happening!" after seeing the output. :)
     
  9. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,945
    One must work through the six stages of debugging:
    1. DENIAL. That can’t happen.
    2. FRUSTRATION. That doesn’t happen on my machine.
    3. DISBELIEF. That shouldn’t happen.
    4. TESTING. Why does that happen?
    5. GOTCHA. Oh, I see.
    6. RELIEF. How did that ever work?
    You may laugh now, but it will really seem hilarious to you after the 1000th time it happens.
     
    Bunny83, Quincey and Joe-Censored like this.
  10. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    Laughing because I went through this yet again just last night. I've had a frustrating bug in my game for almost 2 years I've tried and failed to properly resolve several times. Finally got to #6 with it, so very happy even though the issue wasn't a big problem :p
     
    Kurt-Dekker likes this.
  11. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,945
    It really is like getting a painful splinter out.

    My current record (and it's nothing to be proud of) was a crash bug in my Gravity Well game.

    I wrote the game (and the bug) in 1992 and the game ran fine for all these decades.

    In the past few years as I started porting to Unity and playing it on higher-resolution screens, it became possible to maneuver near the edges of the world and throw a bomb far enough that it would reach out of the heightmap table and crash.

    I fixed that in 2018, so 26 years approximately.

    Software engineering really is something else. Nothing like it.
     
    Joe-Censored likes this.
  12. unity_9E09E226C1D4C1829433

    unity_9E09E226C1D4C1829433

    Joined:
    Feb 17, 2022
    Posts:
    2
    hello i am having a problem with a script. what i am trying to do is have a script which can take a string entered in an input field which needs to be a number or integer and then take that string entered into the input field and turn it into an integer so i can take that value and change a integer value in another script. here is the file. if you have a better way of doing this please let me know. here is the script:

    using System.Collections;
    using System;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI;
    using TMPro;
    using UnityEngine.SceneManagement;
    public class sandboxscript : MonoBehaviour
    {

    public GameObject manager;
    private string enemiescount;
    private string enemiescount1;
    private string enemiescount2;
    private string enemiescount3;
    public int enemycounter;
    public int enemycounter1;
    public int enemycounter2;
    public int enemycounter3;
    public GameObject Canvas;
    public GameObject otherCanvas;
    public GameObject Player;
    public GameObject camera;
    public int scenenumber;

    public TMP_Text inputtext;
    public TMP_Text inputtext1;
    public TMP_Text inputtext2;
    public TMP_Text inputtext3;

    public GameObject othermanager;
    // Start is called before the first frame update
    void Start()
    {

    Canvas.active = true;
    otherCanvas.active = false;
    Player.active = false;
    camera.active = true;
    manager.active = false;
    enemiescount = inputtext.text.ToString();
    enemiescount1 = inputtext1.text.ToString();
    enemiescount2 = inputtext2.text.ToString();
    enemiescount3 = inputtext3.text.ToString();
    }

    // Update is called once per frame
    void Update()
    {
    manager.GetComponent<Spawner>().m_quantity = enemycounter;
    manager.GetComponent<spawner2>().m_quantity = enemycounter1;
    manager.GetComponent<spawner3>().m_quantity = enemycounter2;
    manager.GetComponent<spawner4>().m_quantity = enemycounter3;
    othermanager.GetComponent<killcount>().otherkills = enemycounter + enemycounter1 + enemycounter2 + enemycounter3;

    }

    public void startgame(){
    Canvas.active = false;
    otherCanvas.active = true;
    manager.active = true;
    Player.active = true;
    camera.active = false;


    }

    public void getint1(){
    int.TryParse(enemiescount, out enemycounter);
    enemycounter = int.Parse(enemiescount);

    }
    public void getint2(){
    int.TryParse(enemiescount1, out enemycounter1);
    enemycounter1 = int.Parse(enemiescount1);

    }
    public void getint3(){
    int.TryParse(enemiescount2, out enemycounter2);
    enemycounter2 = int.Parse(enemiescount2);

    }
    public void getint4(){
    int.TryParse(enemiescount3, out enemycounter3);
    enemycounter3 = int.Parse(enemiescount3);

    }

    public void gomenu(){
    SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex - scenenumber);
    }
    }
     

    Attached Files:

  13. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,945
    Please don't necro post. Start your own post. When you post, keep this in mind:

    How to report your problem productively in the Unity3D forums:

    http://plbm.com/?p=220

    This is the bare minimum of information to report:

    - what you want
    - what you tried
    - what you expected to happen
    - what actually happened, especially any errors you see
    - links to documentation you used to cross-check your work (CRITICAL!!!)

    If you post a code snippet, ALWAYS USE CODE TAGS:

    How to use code tags: https://forum.unity.com/threads/using-code-tags-properly.143875/