Unity-如何在运行时将源代码添加到ParentConstraint

时间:2019-05-08 11:06:18

标签: c# unity3d constraints

如何在运行时将GameObject(或Transform-> object.transform)添加到父约束组件? https://docs.unity3d.com/ScriptReference/Animations.ParentConstraint.html

在检查器中,Unity显示父控件组件将“变换”作为源,如下图所示。在代码中,ParentConstraint.AddSource需要一个ConstraintSource对象。但是尝试在代码中尝试这样做,它抱怨constraintSource不能是Transform

https://drive.google.com/open?id=1YOdCQj6MWKgZkgfkaw0DDV5SlI_Apd35

ConstraintSource mySource = m_RealObjOnPlane.transform;//error - can't convert Transform to Animations.ConstraintSource

Xaxis.GetComponent<ParentConstraint>().AddSource(mySource);//AddSource only takes a ConstraintSource 

预计我可以在运行时更改父控件的来源

1 个答案:

答案 0 :(得分:1)

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);
}

所以在您的情况下,应该是这样的

mySource.sourceTransform = m_RealObjOnPlane.transform;