这是玩家脚本中的方法,它捕获光标下的敌人并创建一个导弹来跟踪它。
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 10, 1<<8))
{
FollowEnemy missile = Instantiate(bullet, transform.position, transform.rotation) as FollowEnemy;
// runs perfectly, can change the value of hit.transform
Transform temp = hit.transform;
temp.position = transform.position;
// enemy is a public variable(GameObject)
missile.enemy = temp.gameObject;
// and here comes "NullReferenceException: Object reference not set to an instance of an object"
}
}
FollowEnemy 是导弹上的脚本。为什么我不能将我获得的 gameobject
分配给另一个类中的公共(public)变量?
最佳答案
您不想将导弹实例化为 FollowEnemy
,而是实例化为具有 FollowMissile
组件的 GameObject
。
GameObject missile = (GameObject)Instantiate(bullet, transform.position, transform.rotation);
...
missile.GetComponent<FollowMissile>().enemy = temp.gameObject;
关于c# - 为什么我不能将一个游戏对象分配给另一个游戏对象的公共(public)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36247358/