- Home /
Targetting two objects at once
Im trying to make it so the player can store two objects as targets, the issue I am having with this, is that when I target one object it selects that object twice.
function Combine()
{
var ray : Ray = camera.ViewportPointToRay (Vector3(0.5,0.5,0));
var hit : RaycastHit;
if ((Physics.Raycast (ray, hit)) && (combineTargetOne == null) && (hit.collider.gameObject.tag == "Cube1"))
{
Debug.Log("target one acquired");
combineTargetOne = hit.collider.gameObject;
}
if ((Physics.Raycast (ray, hit)) && (combineTargetOne != null) && (combineTargetTwo == null) && (hit.collider.gameObject.tag == "Cube1"))
{
Debug.Log("target two acquired");
combineTargetTwo = hit.collider.gameObject;
}
}
I have tried a few different ways to get around this, such as using return; or break; to exit out of the function once the first target has been acquired, and changing the 2nd part of the function to an else, or an if else statement - but none of this works for me :( Kinda newbie at raycasting as well, maybe there is a better way to handle this?
Answer by whydoidoit · Oct 09, 2012 at 06:39 AM
Well I'm guessing your code is called often? In response to some kind of user input?
Anyway the best way to make sure it doesn't select the same object twice is to check!
if ((Physics.Raycast (ray, hit)) && (combineTargetOne != null) && hit.collider.gameObject != combineTargetOne && (combineTargetTwo == null) && (hit.collider.gameObject.tag == "Cube1"))
{
Debug.Log("target two acquired");
combineTargetTwo = hit.collider.gameObject;
}
Answer by Loius · Oct 09, 2012 at 05:23 AM
Physics.Raycast returns true if it hits anything. You need to look at the values in hit, which are set by .Raycast.
You do also need if/else so they don't both fill up at once. You can use the 101/010 button to format code so that it's readable, too, which will help us to find issues.
Your answer
Follow this Question
Related Questions
How to read note by pressing "E" using RayCast only? 1 Answer
Need help combining code 1 Answer
Launching a Projectile to a Raycast 1 Answer
Raycasting Problems... 1 Answer
C Sharp Clickable Object 1 Answer