Running start scripts in order

I have a level controller that sets up some initial things. It spawns a car as the player and also the speedometer for the car. Unfortunately the speedo script runs a fraction before the car is instantiated and I get an error when I try to Find object by tag “Car”.

How can i get my spawnCar script to run before my speedo script so it can find the can for the speedo. They are all on the same gameobject and speedo is at the bottom.

Thanks

You can use the Awake() method to setup the initial things and then the Start() that is executed after the Awake().
Another solution is to use some async function, like this:

you can use Invoke method to invoke your code later.Something like this will work i think.

void levelcontroller(){
spawncar();
}
void spawncar(){
Invoke("spawnspeedometer" , 1.0f);
}
void spawnspeedometer()
{
}

This can invoke your method 1 sec after car is spawned. You can also use if condition in code of spawning speedometer.

bool carisspawned;
void spawncar(){

carisspawned = true ;
}

void spawnspeedometer()
{
if(carisspawned)
     spawnspeedometer

 }

Edit → Project Settings → Script Execution Order

Without code from your project it is difficult to suggest an exact solution, so I must resort to generalities on the subject of synchronization.

You mention these are “all on the same GameObject”, which implies they are referenced as member of a GameObject class. Without code I can’t really understand exactly what is meant by “speedo is at the bottom”, though I infer this means the member variable for the speedo is the last given in the owning GameObject.

That said, is speedo a GameObject? I can assume car must be, else you couldn’t hope to find it by tag.

It seems that since code is instantiating both car and speedo at runtime, you’re in control of the order in which these are created. Without code I can’t tell what does what here, but perhaps you could ensure the car is instantiated first.

Is the car the parent of speedo ultimately?

Perhaps the simplest solution is to accept the order you’ve created thus far, and instead of having speedo find the parent, move that “connection” logic to the car, where it should then find the speedo.

Another approach is to hold initialization and allow mutual discovery. That is, if speedo can’t find the car, just skip the initialization for that moment. When car is initializing, fashion a way for it to discover speedo hasn’t initialized and try to find the speedo. In this way the speedo tries, and the car tries, and one should win by being the second to perform the attempt.