• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by MrWolgr · Oct 21, 2013 at 10:23 PM · c#programmingcarsmechanics

Multiple Cars not working

I'm working on some basic codes for cars in the game, when there's only one car it works fine, but the moment I add another everything gets weird. I can get in the first car and get out fine , but when I get out of the second car I appear next to the first car. And when I get into the second car first and get out I'm sent to the edge of the map, where I precede to fall off the map.

I've been working on with this for a good while, but I'm utterly lost on this one. The scripts auto-disable themselves whenever I'm out of the vehicles, and I use a static external script to store character data like which car I get in, the position of it, etc.

Relevant code:

basiccar.cs (car script)

 using UnityEngine;
 using System.Collections;
 
 public class basiccar : MonoBehaviour {
     
     public float maxspeed;
     public float maxturnnorm;
     public float maxturnbrake;
     public float acceleration;
     public float turning;
     public float brake;
     public float mass;
     public float g;
     public GameObject cam;
     public Vector3 carpos;
     public WheelCollider backleft;
     public WheelCollider backright;
     public WheelCollider frontleft;
     public WheelCollider frontright;
     
     public static bool _active;
     public static bool _moving;
     public static bool _braking;
     public static bool _grounded;
     public static bool _idle;
     public static bool _occupied;
     public static float _speed;
     public static float _airspeed;
     public static float _airturn;
     public static float _turn;
     public static float _disground;
     public static float _maxturn;
     public static float _maxspeed;
     
     void Start () {
         _maxturn = maxturnnorm;
         _maxspeed = maxspeed;
         _occupied = false;
         _moving = false;
         _braking = false;
         _grounded = true;
         _idle = true;
         _speed = 0.0f;
         _airspeed = 0.0f;
         _airturn = 0.0f;
         _disground = collider.bounds.extents.y;
         transform.rigidbody.mass = mass;
         wait(2);
         this.enabled = false;
     }
     void Update () {
         //Debug.Log(Input.GetAxis("Vertical")+" & "+_speed + " & " + _turn);
         transform.rigidbody.AddForce(-Vector3.up * g);
         _grounded = isgrounded();
         if(_active && _globalvars._curcar == transform.gameObject) {
             carpos = _globalvars._curcar.transform.position;
             if(Input.GetAxis("Vertical") > 0.01f) {
                 _speed += acceleration/50f;
             }else if(Input.GetAxis("Vertical") < -0.01f) {
                 _speed -= acceleration/25f;
             }else if(Input.GetAxis("Vertical") > -0.01f && Input.GetAxis("Vertical") < 0.01f){
                 if(_speed > 0.8f) {
                     _speed -= acceleration/25;
                 }else if(_speed < -0.8f) {
                     _speed += acceleration/25;
                 }else{
                     _speed = 0.0f;
                 }
             }else{
                 Debug.Log("Error with user input.");
                 _speed = 0.0f;
             }
             if(Input.GetAxis("Horizontal") > 0.01f) {
                 _turn += turning/25f;
             }else if(Input.GetAxis("Horizontal") < -0.01f) {
                 _turn += turning/25f;
             }else if(Input.GetAxis("Horizontal") > -0.01 && Input.GetAxis("Horizontal") < 0.01){
                 if(_turn > 0.8f) {
                     _turn -= turning/25f;
                 }else if(_turn < -0.8f) {
                     _turn += -turning/25f;
                 }else{
                     _turn = 0.0f;
                 }
             }else{
                 Debug.Log("Error with user input.");
                 _turn = 0.0f;
             }
             if(Input.GetButton("Sprint") && _grounded) {
                 _maxturn = maxturnbrake;
                 if(_speed > 2.0f) {
                     _speed -= brake/50;
                 }else if(_speed < -2.0f) {
                     _speed += brake/50;
                 }else{
                     _speed = 0.0f;
                     _maxturn = maxturnnorm;
                 }
             }else{
                 _maxturn = maxturnnorm;
             }
             if(_speed > _maxspeed) {
                 _speed = _maxspeed;
             }
             if(_turn < -_maxturn) {
                 _turn = -_maxturn;
             }else if(_turn > _maxturn) {
                 _turn = _maxturn;
             }
             if(_grounded) {
                 _airspeed = _speed;
                 _airturn = _turn;
             }else{
                 _speed = _airspeed;
                 _turn = _airturn;
             }
             float x = Time.deltaTime * _speed;
             float r = Input.GetAxis("Horizontal") * Time.deltaTime * _turn;
             transform.Translate(x,0,0);
             transform.Rotate(0,r,0);
         }
     }
     
     public void activate(bool a, GameObject player, GameObject c) {
         Debug.Log(_globalvars._curcar);
         Debug.Log(player);
         _active = a;
         cam.active = a;
         if(c != null) {
             _globalvars.setDriving(a, c, c.transform.position);
         }else{
             _globalvars.setDriving(a, null, carpos);
         }
         Vector3 pos = _globalvars._curcarpos;
         player.transform.position = new Vector3(pos.x, pos.y, pos.z + 4);
         player.active = !a;
         if(a == false) {
             wait(2);
             this.enabled = a;
         }
     }
     
     public bool isgrounded() {
         return Physics.Raycast(transform.position, -Vector3.up, _disground + 1);
     }
     
     IEnumerator wait(int time) {
         yield return new WaitForSeconds(time);
     }
 }


custom_Keys.cs (custom keys for player)

 using UnityEngine;
 using System.Collections;
 
 public class custom_Keys : MonoBehaviour {
     
     private basiccar car = new basiccar();
     private raycasting rays = new raycasting();
     
     void Start () {
     }
     
     void Update () {
         if(Input.GetButton("Pause")) {
             Application.Quit();
         }
         if(Input.GetButtonUp("Use")) {
             if(rays.getTag(2f, transform) == "Car") {
                 var cucar = rays.returnlast();
                 car = cucar.GetComponent<basiccar>();
                 car.enabled = true;
                 car.activate(true, transform.gameObject, cucar);
             }else{
                 Debug.Log("Nothing found");
             }
         }
     }
 }


keys_vehicle.cs (set keybindings while in vehicle)

 using UnityEngine;
 using System.Collections;
 
 public class keys_vehicle : MonoBehaviour {
     
     private basiccar car;
     public GameObject player;
     
     void Start () {
         car = transform.GetComponent<basiccar>();
     }
     
     void Update () {
         if(basiccar._active) {
             if(Input.GetButtonDown("Use")) {
                 car.activate(false, player, null);
             }
         }else if(!basiccar._active) {
             
         }else{
             
         }
     }
 }


_globalvars.cs (character settings and variables)

 using UnityEngine;
 using System.Collections;
 
 public class _globalvars : MonoBehaviour {
     
     //Basics
     public static float _health;
     
     //Weapons
     public static int _ammo_pistol;
     public static int _ammo_assault;
     public static int _ammo_sniper;
     public static int _ammo_grenade;
     public static int _ammo_rockets;
     
     //Vehicles
     public static bool _isdriving;
     public static bool _isflying;
     public static GameObject _curcar;
     public static Vector3 _curcarpos;
     public static GameObject _curplane;
     public static Vector3 _curplanepos;
     
     void Start() {
         //Basics
         _health = 100f;
         
         //Weapons
         _ammo_pistol = 0;
         _ammo_assault = 0;
         _ammo_sniper = 0;
         _ammo_grenade = 0;
         _ammo_rockets = 0;
         
         //Driving
         _isdriving = false;
         _isflying = false;
         _curcar = null;
         _curplane = null;
     }
     
     public static void setDriving(bool a, GameObject b, Vector3 c) {
         _isdriving = a;
         _curcar = b;
         _curcarpos = c;
     }
     
     public static void setFlying(bool a, GameObject b, Vector3 c) {
         _isflying = a;
         _curplane = b;
         _curplanepos = c;
     }
 }


If someone can help me that'd be amazing.

Comment
Add comment · Show 2
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Benproductions1 · Oct 22, 2013 at 12:22 AM 0
Share

Your code is really hard to read and understand. You should add a lot more comments (useful comments!) and you should also say how these scripts are set up etc...

avatar image ironblock · Feb 19, 2017 at 05:12 PM 0
Share

ti make reading sutch scripts easyer you can do stuf like add comments and using the , in your variables like this. (also note the camel casing).

public WheelCollider backLeft , backRight , frontLeft , frontRight;

you can also make sepperate functions that you call in the update so its easer to isolate pieces of code and makes it allot easer on the eye. like this:

 void Update ()
 {
 DriveStuff();
 }
 
 void DriveStuff()
 {
 // code
 }

good luck and have fun program$$anonymous$$g

1 Reply

· Add your reply
  • Sort: 
avatar image
14
Best Answer

Answer by VesuvianPrime · Oct 22, 2013 at 02:53 AM

Your problems are because of the way you're using static variables for things like _occupied.

Static variables in C# are variables that are stored on the class, not on the instance:

 public class A
 {
     public static int foobar = 0;
 }
 
 A a = new A();
 A b = new A();
 
 a.foobar = 1;
 
 Debug.Log(b.foobar);

The output is 1.

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image MrWolgr · Oct 23, 2013 at 10:44 PM 0
Share

Oh wow thanks so much. That never even occurred to me. I'll make sure to remember that. Thanks!

avatar image LDev77 · Jan 10, 2015 at 04:25 PM 0
Share

Thanks, I also had a problem with my static variables named 'text_money' since I couldn't inherit 2 things at once. Actually, that just gave me an idea! if I do: using UnityEngine; using System.Collections; class $$anonymous$$ain: $$anonymous$$onoBehavior { public GameObject projectile = new GameObject(); } class Other: $$anonymous$$ain { // Other inherits main and mono behavior! }

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

19 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

How would i slow a car down when it hit off road on a track 3 Answers

Throw 3D object parabolically -> From 2D Canvas to WorldSpace 1 Answer

Index Out of Range Exception - can't figure it out 1 Answer

Distribute terrain in zones 3 Answers

programming help/teacher? c# 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges