【问题标题】:how to search for a game object then zoom the camera to point on that object using an input box unity?如何搜索游戏对象,然后使用输入框统一缩放相机以指向该对象?
【发布时间】:2018-01-28 21:41:01
【问题描述】:

我正在构建一个模拟,它需要 一个搜索框,用户可以在其中输入游戏对象的名称,并且相机应该会自动放大该对象Unity 5 场景。但是我尝试了多个脚本但没有运气。

下面的代码是我认为可以解决这个问题的,但它没有!

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

public class drone_camera_lookup : MonoBehaviour {

    public float minX = -360.0f;
    public float maxX = 360.0f;

    public float minY = -45.0f;
    public float maxY = 45.0f;

    public float sensX = 100.0f;
    public float sensY = 100.0f;

    float rotationY = 0.0f;
    float rotationX = 0.0f;
    public GameObject drone;
    public GameObject actual;
    public GameObject instance;
    var gameObjectTag;

    void Update () {

          //  drone = Resources.Load("drone_with_controller") as GameObject;
            drone = GameObject.FindGameObjectWithTag(gameObjectTag);
            actual = this.drone.GetComponent<GameObject>();
            instance = Instantiate(actual, transform.position, transform.rotation) as GameObject;

            rotationX += instance.transform.localEulerAngles.x * sensX * Time.deltaTime;
            rotationY += instance.transform.localEulerAngles.y * sensY * Time.deltaTime;
            rotationY = Mathf.Clamp (rotationY, minY, maxY);
            transform.localEulerAngles = new Vector3 (-rotationY, rotationX, 0);    

    }
}

显示的错误是:NullReferenceException: Object reference not set to an instance of an object

理想情况下,我想让脚本为对象设置相机动画。提前谢谢你。

【问题讨论】:

  • actual = this.drone.GetComponent&lt;GameObject&gt;(); 没有意义。 drone已经是一个游戏对象!另外,GameObject 没有扩展 Component,因此该方法返回 null。
  • 除了@Draco18s GameObject.FindGameObjectWithTag(gameObjectTag); 的注释之外,如果您没有在其他任何地方初始化gameObjectTag,很可能会返回一个空对象。

标签: c# unity3d


【解决方案1】:

嘿,伙计们,我设法通过将此代码添加到我的相机来解决我的问题,脚本从输入框接收输入,然后使用 wrld3d API 为相机设置动画效果,对我来说非常顺利:-)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Wrld;
using Wrld.Space;

public class focus_drone : MonoBehaviour {
    public Text drone_input; 
    public Transform target;
    private Camera cameraX;

    void Start()
    {
   string drone_id = drone_input.text.ToString();
   target = GameObject.Find(drone_id).transform;
   transform.LookAt(target); 

    }

    void Update()
    {
        string drone_id = drone_input.text.ToString();
        // Rotate the camera every frame so it keeps looking at the target
        target = GameObject.Find(drone_id).transform;
        transform.LookAt(target);
        var destLocation = LatLong.FromDegrees(13.746863, 100.538847);
        Api.Instance.CameraApi.AnimateTo(destLocation, distanceFromInterest: 30, headingDegrees: 0, transitionDuration: 0.5, jumpIfFarAway: false);
    }
}

我希望遇到与我相同的问题的人会发现这很有用。

【讨论】:

    猜你喜欢
    • 2020-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多