Reputation: 21
I have a car in my game with 4 wheels(Unity3D):
Also i have a trigger of EndLevel:
But after when im going throght the trigger its trying to work 4th times How can i change it?
I tried to add my "Player(car)" inside EndGame object but its didnt fix my problem.
using UnityEngine;
public class EndTrigger : MonoBehaviour
{
public GameManager gameManager;
void OnTriggerEnter()
{
gameManager.CompleteLevel();
}
}
Upvotes: 2
Views: 3139
Reputation: 90862
First of all note that OnTriggerEnter(Collider other)
requires a parameter of type Collider
otherwise it wouldn't get called at all.
The simplest solution might be adding a bool
flag as already mentioned by Eric Warburton's answer.
I would prefer to rather tackle the origin of the issue and suggest using different Layers and then configure the Layer-based collision detection via the Edit→ProjectSettings→Physics→ Layer Collision Matrix
.
Create a Layer e.g. END
and assign it to your goal collider object. Make this object not Is Trigger
and rather attach your script checking for OnTriggerEnter
here.
Create a Layer e.g. Player
create a new dedicated invisible object with a collider and enable Is Trigger
here. This object has the only purpose of colliding with the goal collider nothing else. Assign the Player
layer here.
Configure the collision matrix thus that END
only collides with Player
and nothing else. And Player
only collides with END
and nothing else - or maybe later another effect layer like e.g. PowerUps
;)
You can create up to 24 custom layers and make use of the already existing ones so this should hold up a while
Another alternative to the Layers is using Tags
As previously I would make the END
object not a trigger but rather use one on the Player.
Then you can simply compare the tag using CompareTag
void OnTriggerEnter(Collider other)
{
if (!other.CompareTag("Player")) return;
gameManager.CompleteLevel();
}
in very very complex games this might be sometimes better since you can create a lot more Tags than Layers.
Upvotes: 2
Reputation: 329
Well there are a few things that I can think of trying.
You can make sure that only one of your colliders is a trigger. There should be a bool check in the properties to uncheck for your wheels.
You can also do something like creating a counter or a bool that prevents the OnTriggerEnter() from firing multiple times if you only want it to fire once. You can reset it at the start of levels if needs be.
Something like
void OnTriggerEnter()
{
if (!gameManager.IsLevelComplete)
gameManager.CompleteLevel();
}
Inside the gameManager script
public bool IsLevelComplete { get; set; }
public void CompleteLevel()
{
IsLevelComplete = true;
//Do stuff
}
Upvotes: 0