I don't know the easiest way to explain why your code is not working but I will try.
You have two GameObjects:
GameObject A with doDamage
variable.
GameObject B with doDamage
variable.
When GameObject A collides with GameObject B:
A.The OnCollisionEnter2D
function is called on GameObject A.
if(other.gameObject.tag == "Target" && doDamage)
executes because doDamage
is true.
B.The doDamage
variable from GameObject A is then set to false
.
This does not affect the doDamage
variable from GameObject B.
Then
C.The OnCollisionEnter2D
function is called on GameObject B.
if(other.gameObject.tag == "Target" && doDamage)
executes because doDamage
is true.
D.The doDamage
variable from GameObject B is then set to false
.
Both your damage code will run because doDamage
is always true in each OnCollisionEnter2D
call. What you are currently doing is only affecting doDamage
variable in each individual script.
What you are currently doing:
Setting doDamage
in the local/this script to false
while also checking if local/this doDamage
is set or not.
What you need to do:
Set doDamage
in the other script to false
but read the local/this doDamage
to check if it is set or not.
This is what it should look like:
public class DamageStatus : MonoBehaviour
{
bool detectedBefore = false;
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.CompareTag("Target"))
{
//Exit if we have already done some damage
if (detectedBefore)
{
return;
}
//Set the other detectedBefore variable to true
DamageStatus dmStat = other.gameObject.GetComponent<DamageStatus>();
if (dmStat)
{
dmStat.detectedBefore = true;
}
// Put damage/or code to run once below
}
}
void OnCollisionExit2D(Collision2D other)
{
if (other.gameObject.tag == "Target")
{
//Reset on exit?
detectedBefore = false;
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…