Set ConstantForce in Script?

I added a ConstantForce component to a 3D capsule. When I change Force and Torque values in the Inspector, it works great. Of course, I want to change the values under program control. When I print the values in the Console, I see the values that were set in the Inspector, but I can’t seem to change them. If I don’t use “Set”, I get an error from MonoDevelop.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class VehicleControl : MonoBehaviour {
    public GameObject vehicleObject;

    // Use this for initialization
    void Start () {
//        vehicleObject.AddComponent <ConstantForce > ();
        StartCoroutine ("ChangeThrust");       
    }

    IEnumerator ChangeThrust () {
        for (;;) {
            vehicleObject.GetComponent <ConstantForce > ().force.Set (2f, 3f, 4f);
            print ("ForceStart: " + vehicleObject.GetComponent <ConstantForce >().force );
            yield return new WaitForSeconds (.5f);
        }
    }
}

==============================================================
Here is the output I get in the Console:

ForceStart: (0.0, 10.0, 0.0)

UnityEngine.MonoBehaviour:print(Object)
<ChangeThrust>c__Iterator0:MoveNext() (at Assets/VehicleControl.cs:17)
UnityEngine.MonoBehaviour:StartCoroutine(String)
VehicleControl:Start() (at Assets/VehicleControl.cs:11)

These are the same values I entered in the Inspector.

If I remove the ConstantForce component in the Inspector and add it via script, I get zero’s for all the values. I still can’t change the values with the above code. I also tried making the changes in Update instead of a Coroutine. Same results.

Please use proper code tags here. There is a link pinned in the forums about it. Tells you how to do it :slight_smile: It’s much easier for people to read what you’re talking about …

try to change : vehicleObject.GetComponent <ConstantForce > ().force.Set (2f, 3f, 4f);
to this:

vehicleObject.GetComponent <ConstantForce > ().force = new Vector3(2f, 3f, 4f);

I"m not sure what you’re talking about changing it in a coroutine or update or whatever, but once this part’s working, if you have more questions, you can ask.

2 Likes

Thanks for the quick reply. I started with the line you had, but forgot to add “new”. Duh! I have not used C# prior to working with Unity, so did not think about it. I am surprised force.Set does not do that, but anyway this fixed the problem.

This is also my first post. I will read the docs on code tags and add them. Thanks for the pointer!

No problem. ) Glad you got it working. There are many posts around here about how/why that is, etc…
You are certainly not the first person confused by that.
For now, it’s enough to remember how to do it, and if you feel like it, you can look into why :wink:

Cheers, and have fun :slight_smile: