How to check which gameobject is the player using

In my game I have five cars. One if the car is given to player as a default car. But if the player buys another and playes with it how do I check which car is the player using and how do I mention the player? Is there any method like this

If (player(or something else which defines player) using Car 1) { //Do these steps } Thankyou

@Ashmit2020

Assuming that the Player script has access to the Car script under your car Prefab, you could add a status variable (boolean) to the Car script isInUse or something to that effect. Each Car prefab would have its own instance of the script and therefore its own in use flag.

Another option is creating a CarManager script as well that would handle updating the Player’s selected car and the Car’s in use status. If done correctly CarManager would eliminate the need for the in use flag.

I expect you have this data somewhere, when a player buys a car what data are you changing? At some point you’re probably saying something along the lines of “void buycar (newCar) { player.car = newCar }”

The question is then just how do you get the data from there to the point at which you need it. This is a problem you’ll encounter a lot in software development and not doing this in a nice manner is where a lot of codebases start to become unwieldy spaghetti. The answer will depend heavily on what code you have currently:

I would advise having some sort of player handler that contains a set of all players available so that you can call “PlayerController.GetPlayer(0).Car” or something similar

I would not advise holding references to all players elsewhere, so no “public GameObject PlayerOne, PlayerTwo, etc.” in parts of the code whose sole job is NOT to manager player objects. I would not advise checking this by looking at what gameobjects are present under various player gameobjects, doing this check in code is cleaner :slight_smile:

If you want more help then plz send code!