I am creating a racing game; how do I make it so that if an object comes in contact with the collider, the collider tells what place it is in(1,2,3,4,5). And then the collider does a function; for example–if a car is in 5th place, how do i script in C# to make the NavMeshAgent speed of the 5th place car faster.
You’ll need something like a raceManager that will know all the racing cars, and each car will have to know it’s own position in the race.
So Car.cs needs to have a
public int position;
public float distance;
RaceManager.cs needs to have a list of all racing cars and the end line of the track.
public Transform endLine;
private List<Car> allRacingCars = new List<Car>();
void Update()
{
foreach(Car __car in allRacingCars)
{
__car.distance = Vector3.Distance(transform.position, endLine.position);
}
allRacingCars.Sort((car1, car2) => car1.distance.CompareTo(car2.distance));
//Since the cars are sorted out by distance from the endLine
//their position in the list is the same as their position in the race.
foreach(Car __car in allRacingCars)
{
__car.position = allRacingCars.IndexOf(__car);
}
}
The Collider cs that you want to be able to increase the agent speed, will need a:
void OnTriggerEnter(Collider p_other)
{
//You can compare tag if don't want to use getcomponent
//every triggerEnter.
Car __car = p_other.GetComponent<Car>();
if (__car != null)
{
if(__car.position == 5 /*or whatever is the last position*/)
{
__car.GetComponent<NavMeshAgent>().speed += /*amount*/;
}
}
}
For some reason it is not working. So far I only have 2 cars and I put the car script on them both. I put the racemanager on an empty gameobject. I also put the finish line which is a block as the endline for testing and that still did nothing. And finally i attached the trigger script to the trigger which is also a block with out a box render. Any solutions?