- Home /
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.
i mean like a line of code that says something like
target = whatever i just clicked on;
Answer by crazyKnight · Dec 27, 2011 at 08:50 AM
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;
}
}
}
Im trying to do the same thing, where I click on an object and it stores it as a variable, so I copied and pasted the code, and I looked up Raycasting. This code doesnt work for me becuase the ray variable is what defines the ray, and you left it blank. I am new to scripting and i need help filling in the ray variable. Thanks
Answer by Sirex · Dec 27, 2011 at 12:00 PM
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)
Answer by gregzo · Dec 27, 2011 at 08:49 AM
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!