I have an OnTriggTrenter2D function with two if statements which compares the tag of a trail and power-ups.
But the thing is no matter which trail I collide with ,my player dies and the speed bosst powerup doesnt increase the move speed too. Even if i hit the power up it kills the player.
Pls help…
void OnTriggerEnter2D(Collider2D col)
{
if (!col.CompareTag("Trail"+playerno))
{
CurrentHealth = 0;
OnDeath();
Debug.Log("HIT");
}
else if(col.CompareTag("SpeedBoost"))
{
PlayerMovement.maxSpeed = PlayerMovement.maxSpeed + 4;
//PlayerMovement is another script and maxspeed is a public static float variable.
}
else if (col.CompareTag("Trail"+playerno))
{
Debug.Log("NO HIT");
}
void OnDeath()
{
Dead = true;
DeathParticles.transform.rotation = transform.rotation;
DeathParticles.transform.position = transform.position;
DeathParticles.gameObject.SetActive(true);
DeathParticles.Play();
gameObject.SetActive(false);
}
Okay… I’m not sure why the trail won’t avoid itself - you want to check that the tag is correct.
You could also make the player’s trail ignore itself , using: Unity - Scripting API: Physics2D.IgnoreCollision
I am certain, however, that the reason you won’t get the power up is because of that “if it’s not this trail, then do death”.
Well, the very last one is a scratch (no need to even have it…) if you don’t ask for anything to happen, nothing will
As for the first part, that sounds reasonable. You still have to find your bug with the tag, though.
An alternative, which is often good anyways , is if you have any script that is reliably attached to every trail game object, you could look for that component.
Imaginary code:
TrailScript ts = col.GetComponent<TrailScript>();
if(ts != null) {
// just making this up, but ...
if(ts.ownerGameObject != gameObject) {
// death.
}
}
else if(col.CompareTag("Power Up")) {
// boost speed
}
I’m not saying you have to add that, or that is the best idea… I just wrote it out as an example in case you think it’s something you could use…
I believe GetComponent is often superior to checking tags; however, tags are just sometimes more convenient (and often shown in quick examples, too) .