- Home /
Lock On and Unlocking [3D]
So I wrote the following to have my character face and "lockon" to an enemy when you right click on it
//Enemy Detect Ray
Ray cameraRay = mainCamera.ScreenPointToRay(Input.mousePosition);
RaycastHit rayHit = new RaycastHit();
if (Physics.Raycast(cameraRay, out rayHit))
{
//Detect Lockon
//Lock
if (rayHit.collider.tag == "Enemy" && Input.GetMouseButtonDown(1))
{
lockedEnemy = rayHit.transform.gameObject;
Debug.Log("I've Lockedon to " + lockedEnemy);
isLockedOn = true;
}
//Unlock
if (isLockedOn == true && Input.GetMouseButton(1) || lockedEnemy == null)
{
Debug.Log("Breaking Lockon");
isLockedOn = false;
lockedEnemy = null;
}
}
I tried to create a way you could "unlock" from an enemy or possibly lock onto a different one but the issue I'm having is that when the unlock is enabled, in game when I lock on, it will instantly unlock. What am I doing wrong?
Answer by Cynikal · Apr 04, 2018 at 09:43 PM
You're doing it all in the same frame, the easiest solution here is to put your Unlock code before your Locked On Code..
As currently (all in the same frame) Gets locked on, then checks the unlock, which is still valid since you right clicked.
So, swap your Lock, and your Unlock code's positions, so it goes: Unlock -> Lock.
Unfortunately it looks like I'm still getting the same issue with it locking and unlock in the same frame. Would there be a better way to handle it?
if (Physics.Raycast(cameraRay, out rayHit))
{
//Detect Lockon
//Unlock
if (isLockedOn == true && Input.Get$$anonymous$$ouseButtonDown(1) || lockedEnemy == null)
{
Debug.Log("Breaking Lockon");
isLockedOn = false;
lockedEnemy = null;
}
//Lock
if (rayHit.collider.tag == "Enemy" && Input.Get$$anonymous$$ouseButtonDown(1))
{
lockedEnemy = rayHit.transform.gameObject;
Debug.Log("I've Lockedon to " + lockedEnemy);
isLockedOn = true;
}
}
Your code looks like that? I guess alternatively you can set one to Get$$anonymous$$ouseButtonDown, and the other to Get$$anonymous$$ouseButtonUp, but I think a check would be better, by setting a "OneTimeUse" boolean and checking against it.
Also note, your Unlock was using: "Get$$anonymous$$ouseButton" ins$$anonymous$$d of "Get$$anonymous$$ouseButtonDown"
Answer by Kishotta · Apr 04, 2018 at 10:54 PM
You should use an else if
condition on your unlock block. That way only one of the two blocks will be executed in a single frame.