为什么当我将脚本附加到手电筒时没有发生什么?

时间:2017-04-28 02:16:08

标签: c# unity3d unity5

我想要做的是当手电筒打开时能够用鼠标旋转手电筒。但是当我将脚本附加到手电筒时,我没有得到任何错误,当我移动鼠标时,没有任何事情发生。我试图将脚本附加到GameObject我也尝试将脚本附加到EthanRightHand但没有。

但是,如果我将脚本附加到ThirdPersonController,它将旋转角色。但我想在手电筒打开时只旋转手电筒,或者在手电筒开启时旋转EthanRightHand可能更好。

我可以让第二个脚本中的手电筒成为公共静态。但这不是重点。问题是ObjectRotator仅在ThirdPersonController上工作的第一个脚本。

Hierarchy and Inspector

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

public class ObjectRotator : MonoBehaviour
{
    int speed;
    float friction;
    float lerpSpeed;
    private float xDeg;
    private float yDeg;
    private Quaternion fromRotation;
    private Quaternion toRotation;

    // Use this for initialization
    void Start()
    {
        speed = 3;
        friction = 3f;
        lerpSpeed = 3f;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            xDeg -= Input.GetAxis("Mouse X") * speed * friction;
            yDeg += Input.GetAxis("Mouse Y") * speed * friction;
            fromRotation = transform.rotation;
            toRotation = Quaternion.Euler(yDeg, xDeg, 0);
            transform.rotation = Quaternion.Lerp(fromRotation, toRotation, Time.deltaTime * lerpSpeed);
        }
    }
}

手电筒脚本

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.Characters.ThirdPerson;

public class Flashlight : MonoBehaviour
{

    [SerializeField]
    Transform someBone;

    Light flashlight;

    // Use this for initialization
    void Start()
    {
        flashlight = GameObject.FindGameObjectWithTag("Flashlight").GetComponent<Light>();
        transform.parent = someBone;
    }

    // Update is called once per frame
    void Update()
    {
        transform.localRotation = someBone.localRotation;
        transform.localScale = someBone.localScale;

        if (Input.GetKeyDown(KeyCode.F))
        {
            if (flashlight.enabled)
            {
                flashlight.enabled = false;
            }
            else
            {
                flashlight.enabled = true;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

如果您打算让FlashLight成为Hand的孩子,则需要从代码中删除这两行

  

transform.localRotation = someBone.localRotation;
          transform.localScale = someBone.localScale;

因为它会旋转和缩放FlashLight以及手。