Controlling speed between two different scripts

Hey everybody I’ll try to make it short and clear. I’m working on a game where the player is a deer trying to cross roads. I have already managed to get the cars to spawn on the roads, but I want the cars to drive slower or faster, depending on the level.

This is the script that controls car movement -

This is the script that controls the spawning of cars -

I’m trying to communicate betwen the two scripts (newCarSpeed = carMovement.carSpeed;), and I’m doing this because I can’t edit the carSpeed variable found inside CarMovement.cs on each level as I’d like, since CarMovement.cs only exists on instances of the car prefabs.

But my way of approaching this doesn’t seem to work and I’d appreciate any help.
Thank you! :slight_smile:

Hi TzahiLevin,

Please note, it’s better to copy/paste your code and apply the code fencing characters, rather than using screenshots. Screenshots are ideal for displaying specific details from within a game engine editor or even error messages, but for code, they tend to be less readable, especially on mobile devices which can require extensive zooming and scrolling.

You also prevent those that may offer to help you the ability to copy/paste part of your code back to you with suggestions and/or corrections, meaning that they would need to type a potentially lengthy response. You will often find that people are more likely to respond to your questions if you make it as easy as possible for them to do so.

Hope this helps :slight_smile:

In which course and lecture are you, by the way?


See also:

Hey Nina, thank you for replying!

First of all, you’re right about the screenshots, I’ll take it into consideration the next time I post - good point.

Regarding your question, I am currently doing a Gamedev.tv Blender course, and this is a personal project of mine - I hope it’s okay to ask about it here.

Sure. I just asked because we have so many Unity courses, and I don’t know all of them.

Regarding your problem, look up “Overload Method” on DotNetPerls. That could help you with defining the speed of instantiated car objects during runtime.

I’ll definitly look into it, but I actually solved my problem!

I created a new public variable in CarSpawner.cs called newCarSpeed;
CarSpawner.cs is sitting on a car spawner gameobject, meaning I can edit newCarSpeed in the inspector.

I then got a reference for the CarSpawner script inside CarMovement.cs, and wrote
carSpeed = carSpawner.newCarSpeed in Update, and it worked!

Good job! :slight_smile:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms