x


how to make an object "the target" when you click on it

i have a hovertank thing with rockets and guns and missiles and i have them all shooting at a target (a cube)

i want the target to change to whatever object i click on, does anyone know how to do this? i don't want to have to put a script on every object and then send a message because i will have heaps of things.

more ▼

asked Dec 27 '11 at 08:08 AM

sam32x gravatar image

sam32x
178 38 56 62

i mean like a line of code that says something like

target = whatever i just clicked on;
Dec 27 '11 at 08:13 AM sam32x
(comments are locked)
10|3000 characters needed characters left

3 answers: sort voted first
var hit: RaycastHit;
var ray;
private var target : Transform;

function Update () 
{
    if(Input.GetMouseButtonDown(0))    // for standalone
       {
         if (Physics.Raycast (ray, hit, 100)) 
           {
              if(hit.collider.gameObject.tag == "TagName")
                {
                 target = hit.collider.gameObject;
              }
       }
}
more ▼

answered Dec 27 '11 at 08:50 AM

crazyKnight gravatar image

crazyKnight
869 16 20 30

thankyou lots!

Dec 27 '11 at 09:53 AM sam32x
(comments are locked)
10|3000 characters needed characters left

I would use the unity function OnMouseDown and then change a select variable you can have in a master GUI script.

def OnMouseDown():
    currentPlayersGameObject = GameObject.Find(_gameState.WhosTurn)
    currentPlayer = currentPlayersGameObject.GetComponent[of PlayerScript]()
    if currentPlayer.IsPlayerAI == false:
       currentPlayerGUI = currentPlayersGameObject.GetComponent[of GuiScript]()
       currentPlayerGUI.SetSelected(gameObject)
more ▼

answered Dec 27 '11 at 12:00 PM

Sirex gravatar image

Sirex
91 1 2 5

(comments are locked)
10|3000 characters needed characters left

Search for mouse raycasting, you'll find what you need. The idea is to convert the 2d cursor position in 3d, raycast, and then hit.transform gives you the transform of the object you are pointing. Plenty of examples already out there!

more ▼

answered Dec 27 '11 at 08:49 AM

gregzo gravatar image

gregzo
1.6k 31 41 51

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x3334
x535
x57
x11
x4

asked: Dec 27 '11 at 08:08 AM

Seen: 708 times

Last Updated: Dec 27 '11 at 12:00 PM