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

Best way to select an object

Discussion in 'Getting Started' started by Sparticus, Oct 25, 2019.

  1. Sparticus

    Sparticus

    Joined:
    Mar 15, 2014
    Posts:
    149
    Hey all,

    I'm very new to unity. If I were making a mobile game that had an object (like a box) that i want to allow the player to select and drag it around the screen... what is the best way structure my code...

    Do I :

    1.) Create a script responsible for all touch inputs. On screen touch, that script would then fire a raycast and see if it hit any boxes on the screen. If it does, it will call an "onTouch" method i'd write on the box's script.

    2.) Add a script to the box game object that on update() checks to see if there is any touches on the screen that are touching it

    3.) Add a script to the box game object that has the OnMouseDown() method and it will handle everything itself.

    4.) some other method?


    I come from a Flash game development background where I generally like to have a Main Class responsible for controlling the game. In the games I've made in the past the Main Class would detect a touch and let the game objects know who was touched and what to do next... not sure how that translates to Unity. Option 1 seems the closest to what I am used to... but firing raycasts constantly seems like an expensive operation...

    At the end of the day I'd like to learn the correct way to handle this.

    Thanks!
     
  2. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    Asking what the "best way" to do something on this forum is a bad way to ask your question, because people who have done this before but haven't gone through the trouble of verifying their way is the "best way" aren't going to respond.

    My guess is that you'd have a central script which checks for a touch, then raycasts from the touch point and if the raycast hits an object you care about you take its reference and set that to whatever "selected" variable you're using to keep track of what is selected, and on the object itself you call some method on some script on the object which does something visually to indicate it is selected (changes color, draws a box around it, etc). But I have no idea if this is the "best way".