String to int conversion not working in ControllerCollider method although I am sure it is an int...

Hello,
I’m trying to get the name of an object when I hit it with my Character Controller. The name of the object is always an int. Such as 12

It fails to convert the string retrievedName (which gives successfully 12 in my console).
If I use TryParse instead, I get i = 0. Which tells me that the conversion failed as well…
The script is attached to my FPSController.

Could anyone help me out…?

Here is the code:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class GetName : MonoBehaviour {

private string retrievedName;
private int i;

void Start()
{    }

void OnControllerColliderHit(ControllerColliderHit hit)
{
    if(hit.collider.gameObject.tag == "Station")
    {
        Debug.Log("Hit a Station");
        retrievedName = hit.collider.gameObject.ToString();
        Debug.Log(retrievedName);
        i = int.Parse(retrievedName);
        //int.TryParse(retrievedName, out i);
        //i = System.Int32.Parse(retrievedName);
        Debug.Log("i =" + i);
    }
}

void Update()
{   }

}

The gameObject has no parents, no children and i gave it a name by renaming it in the hierarchy.
There are no space before or after the number.

Since you’re trying to access the name of your gameobject, you may need to Parse the .name property, like so:

retrievedName = hit.collider.gameObject.name;

If that doesn’t work, try Logging everything:

string myName = hit.collider.gameObject.name;
Debug.Log(myName);
Debug.Log(myName.Length);

I’ve had problems with Parse due to there being invisible newline characters at the ends of my strings before. Logging the Length will determine if that’s the case, in which you can solve by either removing it in the hierarchy, or changing it via code with SubString.