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. Dismiss Notice

GUI Texture | Above Object

Discussion in 'Scripting' started by kerperlo, Mar 6, 2016.

  1. kerperlo

    kerperlo

    Joined:
    Mar 6, 2016
    Posts:
    6
    Hello,

    I know you need to have a function of "OnGUI" for this to work. I don't know how to place a(n) texture over an object when the player gets close enough. It has something to do with Raycast or Vector3.Distance?

    Thanks.
     
  2. grimofdoom

    grimofdoom

    Joined:
    Sep 6, 2013
    Posts:
    168
    I have not tested it, but this should be what you are looking for (you can change the Vector3.Distance to Vector2.Distance depending on the usage. Vector2 is 2D/canvas while Vector3 is 3D/WholeGameWorld)

    Code (CSharp):
    1. public class SetTextureOnDistance : MonoBehaviour{
    2.     public GameObject player;
    3.     public GameObject floor;
    4.  
    5.     public Texture newtexture;
    6.     public Texture oldTexture;
    7.  
    8.     public Renderer rend; //QUICK ACCESS AND LESS PROCESSING
    9.  
    10.     void Start(){
    11.         rend = floor.GetComponent<Renderer> ();
    12.     }
    13.  
    14.     void CheckDistance(){
    15.         //BOTH OF THESE WILL PROVIDE A float VALUE FOR DISTANCE BETWEEN 2 OBJECTS
    16.         float distance = Vector2.Distance (player.transform.position, floor.transform.position);
    17.         if (distance < 20) {
    18.             //SET THE TEXTURE TO NEW TEXTURE
    19.             rend.material.mainTexture = newtexture;
    20.         }//SET TEXTURE BACK TO oldTexture IF TOO FAR && NOT ALREADY oldTexture
    21.         else if (distance > 20 && rend.material.mainTexture != oldTexture) {
    22.             rend.material.mainTexture = oldTexture;
    23.         }
    24.     }
    25. }
     
  3. kerperlo

    kerperlo

    Joined:
    Mar 6, 2016
    Posts:
    6
    This kind of helped, but I need the texture to be above the object.
     
  4. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Do you really want to use the legacy system?

    This becomes trivial with the new UI system. Just add a Canvas set to world space as a child of the object. Problem solved.