Runtime Parent Constraint problem 2021.3.8f

Trying to create a Parent Constraint at runtime but it doesn’t seem to work, the child it not inheriting the source movement. The child object is locked and cannot be moved but that as far as it goes.

I can build it in the editor at run time, add a parent constraint in the inspector then add a source and it works but it doesn’t seem to work when done with code, is there something I’m missing?

below is a simple example that doesn’t work but should?

https://stackoverflow.com/questions/56039340/unity-how-add-source-on-runtime-to-parentconstraint

using UnityEngine;
using UnityEngine.Animations;


public class ParentTest : MonoBehaviour
{

ConstraintSource constraintSource;

void Start()
{
    var go = new GameObject("Source");

    var cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
    var parentConstraint = cube.AddComponent<ParentConstraint>();
    constraintSource.sourceTransform = go.transform;
    parentConstraint.AddSource(constraintSource);
   parentConstraint.constraintActive = true;
}

}

any help on how to get this working/what is missing or conformation that it doesn’t work would be very much appreciated.

Many thanks

What does “doesn’t work” mean? Does the transform not move at all, or does it move in an unexpected way?

It looks like you’re not setting a few important fields – check what clicking the Activate button in the inspector does. I’m guessing you’re winding up without the position/rotation offsets.

Also, as a comment on that answer notes, the weight is going to be 0 by default.

Thank you chemicalcrux for your response.

Yes I’ve just worked out what I was doing wrong! doh it was this

“Also, as a comment on that answer notes, the weight is going to be 0 by default.”

needed to add this line to the code " constraintSource.weight = 1;" and now it works as expected.