【发布时间】: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<GameObject>();没有意义。drone已经是一个游戏对象!另外,GameObject 没有扩展 Component,因此该方法返回 null。 -
除了@Draco18s
GameObject.FindGameObjectWithTag(gameObjectTag);的注释之外,如果您没有在其他任何地方初始化gameObjectTag,很可能会返回一个空对象。