我有一个已配置的Configurable Joint,我在Unity3d项目中经常使用它,因此我决定将其配置实现为ConfigurableJoint的子类,如图所示;

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

public class FollowJoint : ConfigurableJoint {

    // Use this for initialization
    void Start () {
        this.anchor = Vector3.zero;
        this.axis = new Vector3 (1, 0, 0);
        this.connectedAnchor = Vector3.zero;
        this.secondaryAxis = new Vector3 (0, 1, 0);
        xMotion = ConfigurableJointMotion.Limited;
        yMotion = ConfigurableJointMotion.Limited;
        zMotion = ConfigurableJointMotion.Limited;
        angularXMotion = ConfigurableJointMotion.Locked;
        angularYMotion = ConfigurableJointMotion.Locked;
        angularZMotion = ConfigurableJointMotion.Locked;

        linearLimitSpring.spring = 100;
        linearLimitSpring.damper = 1;
        linearLimit.limit = 0;
        linearLimit.bounciness = 0;
        linearLimit.contactDistance = 0;

    }
}


但是,这给了我错误“ FollowJoint:无法从密封类型'UnityEngine.ConfigurableJoint'派生”

如果这不可能,为什么?什么是一个好的替代策略(除了实例化可配置的关节并通过代码对其进行配置之外)?

最佳答案

正如您所提到的那样,问题在于:


  FollowJoint:无法从密封类型`UnityEngine.ConfigurableJoint派生


在C#中,不能继承密封类型。

sealed (C# Reference)看到:


  当应用于类时,密封修饰符可防止其他类从其继承。


如何解决这个问题

要解决此问题,可以执行工厂函数,以便轻松地重新创建它:

public static ConfigurableJoint MakeJoint() {
    var joint = new ConfigurableJoint();

    joint.anchor = Vector3.zero;
    joint.axis = new Vector3 (1, 0, 0);
    joint.connectedAnchor = Vector3.zero;
    joint.secondaryAxis = new Vector3 (0, 1, 0);

    // ...

    return joint;
}

// Use factory each time you need the same
var jointA = MakeJoint();
var jointB = MakeJoint();


您还可以通过更改函数的签名以采用参数来改进工厂,并使用参数设置返回的ConfigurableJoint的参数。例如,可以添加而不是使用固定的secondaryAxis使其类似于:

var joint = MakeJoint(secondaryAxis:new Vector3(0, 0, 1));


阅读有关可选和命名参数here的更多信息

10-02 21:49