首页 > 解决方案 > 通过 GetComponentInChildren 访问 Unity3D 可配置关节组件

问题描述

我有一个胶囊和一个由可配置关节连接的球体。我使用胶囊刚体移动玩家,球体充当脚轮(就像带悬架的独轮车)。

由于球体是胶囊的孩子,我正在使用 GetComponentInChildren 尝试访问可配置关节、Y 驱动器、位置弹簧(浮点值)。

我迷路了试图用谷歌搜索这个问题。

这是相关代码,里面的一切都//Comment不起作用:

public class PlayerMovement : MonoBehaviour
{

    private Rigidbody rb;
    public float moveSpeed = 10f;
    public float distanceGround;
    public bool isGrounded = false;
    public bool isCrouch = false;


    void Awake()
    {
        rb = GetComponent<Rigidbody>();
    }

    void Start()
    {
        distanceGround = GetComponent<Collider>().bounds.extents.y;
    }

    void FixedUpdate()
    {
        Movement();
    }

    private void Movement() 
    {
        float inputX = Input.GetAxis("LStickHorz");
        float InputZ = -Input.GetAxis("LStickVert");
        float multiplier = 1f;

        if (!Physics.Raycast (transform.position, -Vector3.up, distanceGround + 1.5f))
        {
            isGrounded = false;
            print("IN AIR.....");
        }
        else
        {
            isGrounded = true;
            print("....onGround");
            //Debug.DrawRay(?,?, Color.red, 1.25f);
        }

        if (Physics.Raycast (transform.position, -Vector3.up, distanceGround + .2f))
        {
            isCrouch = true;
            print("VVVVVVVVVVVVVV");
            //ConfigurableJoint cj = gameObject.GetComponentInChildren(typeof(ConfigurableJoint)) as ConfigurableJoint;
            //set y spring value
            //cj.yDrive.positionSpring = 50f;

        }
        else
        {
            isCrouch = false;
        }

        if (!isGrounded)
        {
            multiplier = .2f;
        }

        if (isCrouch)
        {
            multiplier = .2f;
        }

        Vector3 moveVector = new Vector3(inputX * multiplier, 0.0f, InputZ * multiplier);

        //if ()

        rb.AddForce(moveVector * moveSpeed);
    }
}

标签: c#unity3d

解决方案


让我们从您的第一条评论开始,即 function Debug.DrawRay()。如果您查看此处的文档,它将告诉您函数的所有参数并向您展示一个示例。对于这个函数,前两个参数是位置和方向:

Debug.DrawRay(transform.position, Vector3.up * 5, Color.red, 1.25f)

第二个问题是您不能positionSpring直接设置字段。您需要yDrive在另一个变量中存储对 的引用,更改 的值positionSpring,然后设置yDrive为 temp 变量:

// Get the COnfigurableJoint component
ConfigurableJoint cj = gameObject.GetComponent<ConfigurableJoint>();

// Grab a reference to the JointDrive
JointDrive jd = cj.yDrive;

// Set the value of positionSpring here
jd.positionSpring = 50.0f;

// Apply the changes you made to the yDrive back to the ConfigurableJoint
cj.yDrive = jd;

推荐阅读