Convert a found gameobject's name to a string
So, what I'm trying to do here is get the name of the closest gameobject to the player. (This script is attached to the player and works well):
 // Find all game objects with tag Loot
 var nameofclosestloot = "";
 var gos : GameObject[];
 gos = GameObject.FindGameObjectsWithTag("Loot"); 
 var closestloot : GameObject; 
 var distance = Mathf.Infinity; 
 var position = transform.position; 
 // Iterate through them and find the closest one
 for (var go : GameObject in gos)  { 
 var diff = (go.transform.position - position);
 var curDistance = diff.sqrMagnitude; 
 if (curDistance < distance) { 
 closestloot = go; 
 distance = curDistance; 
 } 
 } 
         
 Debug.Log(closestloot);
 // result is something like 'weap_barrel_short 4 (UnityEngine.GameObject)'
 nameofclosestloot = closestloot;
 // how to convert this to a string variable?
My problem is, the debug result will return 'weap_barrel_short 4 (UnityEngine.GameObject)' for example. If I try to do anything with this like,
 nameofclosestloot = nameofclosestloot.Replace ("(UnityEngine.GameObject)", "");
I get the error Cannot convert 'UnityEngine.GameObject' to 'String'.
So, how do I convert this to a string?
               Comment
              
 
               
               
               Best Answer 
              
 
              Answer by tperry1x · Oct 30, 2015 at 11:18 PM
Ah, got it!
nameofclosestloot = closestloot.name; nameofclosestloot = nameofclosestloot.Replace ("(UnityEngine.GameObject)", ""); Debug.Log(nameofclosestloot);
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                