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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Wall of cubes with mouseovers

Discussion in 'Scripting' started by gudula, Jul 31, 2015.

  1. gudula

    gudula

    Joined:
    May 20, 2015
    Posts:
    125
    Hi

    In 3d I have a wall of Primitive Cubes. If I mouseover a cube I would like to know how I can colour the cube below the mouseover cube to a different colour with unity3d

    Code (csharp):
    1.  
    2. target = Vector3.down???? (cube below mouseover cube)
    3. target.transform.GetComponent<Renderer>().material.color = new Color(0.1f, 0.0f, 0.5f);
    4.  
     
  2. DonLoquacious

    DonLoquacious

    Joined:
    Feb 24, 2013
    Posts:
    1,667
    You could probably raycast from the clicked cube down to the next cube, but a far simpler logic-only solution would be to set up all of your cube references in an array of arrays (also called a 2-dimensional array). If you do that, you can select the "cube below" just by subtracting 1 from the row index.
     
  3. kemar

    kemar

    Joined:
    Nov 4, 2014
    Posts:
    15
  4. gudula

    gudula

    Joined:
    May 20, 2015
    Posts:
    125
    Code (csharp):
    1.  
    2.  if (Physics.Raycast(hit.transform.position, Vector3.down, out hit))hit.collider.gameObject.transform.GetComponent<Renderer>().material.color = new Color(0.1f, 0.0f, 0.5f);  
    3.  
    I got this
     
  5. DonLoquacious

    DonLoquacious

    Joined:
    Feb 24, 2013
    Posts:
    1,667
    Looks fine, aside from really needing to be spread across multiple lines and not crammed into one line like this- and assuming that "hit" is the same name as the RaycastHit that resulting from the current cube being hit. You should change Vector3.down to hit.transform.down though, I believe.
     
  6. _met44

    _met44

    Joined:
    Jun 1, 2013
    Posts:
    633
    you could also check for OnMouseEnter/OnMouseOver/OnMouseExit message on your cubes if you don't intend to do touch screens.

    Alternatively, if your cube wall is of known size and relative to screen size you could i simply divide cursor position by cube size to find out which cube is targeted (very effective performance wize if that's to ever be a concern to your project).
     
  7. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Plenty I good methods listed. I would personally use a physics raycaster, an event system and the IPonterXXX interfaces.

    Just be aware that you can't make mine craft using real cubes. ;)