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

Change texture on click

Discussion in '2D' started by Bioxent, Dec 15, 2014.

  1. Bioxent

    Bioxent

    Joined:
    Nov 24, 2014
    Posts:
    5
    Hello there. I have been trying to make an GameObject change it's texture by clicking it during the game, here what I got so far:
    Code (CSharp):
    1. public GameObject tile; //A cube material with already picked texture
    2. public Texture2D texture1;
    3. public Texture2D texture2;
    4. public void ChangeTexture(){
    5.         tile.renderer.material.mainTexture = texture2;
    6.     }
    7. void Start ()
    8.     {
    9. //Code of loop that generates a grid of tiles
    10. }
    11. void Update () {
    12. if (Input.GetMouseButtonDown (0)) {
    13.             ChangeTexture ();
    14.                 }
    15.     }
    How I can access the texture in the Tile object? How do I can make it respond when the GameObject tile is being clicked? It's located in folder called prefabs. I'd like the function to access it's texture and change it on click.
     
  2. Ilingis

    Ilingis

    Joined:
    Dec 13, 2012
    Posts:
    63
    Use Raycasting:
    http://docs.unity3d.com/ScriptReference/Physics.Raycast.html

    Code (CSharp):
    1. var accessedTexture : Texture2D;
    2.  
    3. function Update() {
    4. var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
    5. var hit : RaycastHit;
    6. if (Physics.Raycast (ray, hit, 100)) {
    7.    if(hit.gameObject == tile)
    8.       {
    9.          accessedTexture = tile.renderer.material.mainTexture;
    10.       }
    11. }
    12. }