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 convert a GameObject to a float?

Discussion in 'Scripting' started by dajewa, Jun 24, 2020.

  1. dajewa

    dajewa

    Joined:
    May 31, 2020
    Posts:
    32
    Idk, if you can do it, but I did an array (with a gameobject) and I was trying to see the distance from one place to another so I used this:
    Code (CSharp):
    1.     void Update() {
    2.         Vector3.Distance(ingrediens.transform.position, Slot[0].transform.position);
    3.         Vector3.Distance(ingrediens.transform.position, Slot[1].transform.position);
    4.         Vector3.Distance(ingrediens.transform.position, Slot[2].transform.position);
    and then I tried to see the smallest number, and for that I used this:
    Code (CSharp):
    1.         Debug.Log(Mathf.Min(Slot[0], Slot[1], Slot[2]));
    and then I got a error, can you tell me what I should do? Thanks for your help! :)
     
  2. WarmedxMints

    WarmedxMints

    Joined:
    Feb 6, 2017
    Posts:
    1,035
    You would need to store the distance value into something and then compare the stored values. Like so;
    Code (CSharp):
    1. var slot0dist = Vector3.Distance(ingrediens.transform.position, Slot[0].transform.position);
    2. var slot1dist = Vector3.Distance(ingrediens.transform.position, Slot[1].transform.position);
    3. var slot2dist = Vector3.Distance(ingrediens.transform.position, Slot[2].transform.position);
    4.  
    5. Debug.Log(Mathf.Min(slot0dist, slot1dist, slot2dist));
    6.  
    If you want to know which object is closer though rather than just the distance it is at, I would iterate through your array and return a reference to the closest one;
    Code (CSharp):
    1. private void Update()
    2. {
    3.     Debug.Log(NearestObject(ingrediens, Slot).name);
    4. }
    5.  
    6. private GameObject NearestObject(GameObject target, GameObject[] ObjectsToCheck)
    7. {
    8.     var dist = Mathf.Infinity;
    9.     GameObject ret = null;
    10.  
    11.     for(var i = 0; i < ObjectsToCheck.Length; i++)
    12.     {
    13.         var distance = Vector3.Distance(target.transform.position, ObjectsToCheck[i].transform.position);
    14.  
    15.         if(distance < dist)
    16.         {
    17.             dist = distance;
    18.             ret = ObjectsToCheck[i];
    19.         }
    20.     }
    21.  
    22.     return ret;
    23. }
    24.  
    25.  
     
    NicBischoff likes this.
  3. dajewa

    dajewa

    Joined:
    May 31, 2020
    Posts:
    32
    Thank you it helped me alot: