如何将实例化对象传递给摄像头

时间:2016-12-10 15:26:06

标签: c# unity3d camera parameter-passing

我正在我的场景中实例化一个物体,现在我想要相机跟着它我该怎么做? 对象被实例化但我不知道如何将对象传递给我的相机目标; 并且您无法将实例化对象拖到检查器

public class TankManager : MonoBehaviour
{
void Start()
{
    Instantiate (MenuManager.SelectedCharacter, Vector3.zero, Quaternion.identity);
}}

我的相机代码:

public class FollowCamera : MonoBehaviour{
public Transform target;
public Vector3 offsetPosition;
public Space offsetPositionSpace = Space.Self;
public bool lookAt = true;

private void Update()
{
    Refresh();
}

public void Refresh()
{
    if(target == null)
    {
        Debug.LogWarning("Missing target ref !", this);

        return;
    }

    if(offsetPositionSpace == Space.Self)
    {
        transform.position = target.TransformPoint(offsetPosition);
    }
    else
    {
        transform.position = target.position + offsetPosition;
    }

    if(lookAt)
    {
        transform.LookAt(target);
    }
    else
    {
        transform.rotation = target.rotation;
    }
}

}

1 个答案:

答案 0 :(得分:2)

您的目标变量是公共的,因此在TankManager脚本中引用它。 假设您将TankManager脚本附加到层次结构中的GameObject,脚本应如下所示:

public class TankManager : MonoBehaviour
{

public Camera camera;
FollowCamera followC;

    void Start()
    {
        GameObject target = Instantiate (MenuManager.SelectedCharacter, Vector3.zero, Quaternion.identity);
        followC = camera.GetComponent <FollowCamera>();
        followC.target = target;
   }
}

然后将相机拖放到TankManager检查器区域。