Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

How to change suspension settings c#

Discussion in '2D' started by cratica, Nov 10, 2019.

  1. cratica

    cratica

    Joined:
    Dec 11, 2016
    Posts:
    12
    Hello, I'm working on a 2D racing game. I need to be able to upgrade the suspension (which changes damping ratio and frequency). However, I haven't been able to find out how to make this work in the game.

    Here is what I have. But again, it has no effect on the car in the game. (if I change the settings in the editor, it of course changes it in the game but I need to be able to change it in code)


    public WheelJoint2D motorWheel;
    public JointSuspension2D jointSuspension;

    void Start () {
    jointSuspension = motorWheel.suspension;
    jointSuspension.dampingRatio = 0.01f;
    jointSuspension.frequency = 0;
    ...
    }

    Thanks for any suggestions!
     
  2. jeffreyschoch

    jeffreyschoch

    Joined:
    Jan 21, 2015
    Posts:
    2,635
    JointSuspension2D is a struct. Structs are passed by value, not by reference like a class.

    So what you're doing is copying the values from "motorWheel.suspension" into your own local struct, not getting a reference to the suspension.

    You're changing values in your local struct, and then you need to copy that new data back into "motorWheel.suspension".

    Add this line at the end of your changes:
    motorWheel.suspension = jointSuspension;


    https://docs.unity3d.com/ScriptReference/JointSuspension2D.html
     
    MisterSkitz, vakabaka and cratica like this.
  3. cratica

    cratica

    Joined:
    Dec 11, 2016
    Posts:
    12
    Wow, thank you so much. I appreciate you taking the time to help me.