这是播放器脚本中的方法,它捕捉光标下的敌人并创建一个跟随它的导弹。
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
分配给另一个类中的公共变量?
答案 0 :(得分:3)
您不希望将导弹实例化为FollowEnemy
,而应将GameObject
实例化为具有FollowMissile
组件的导弹。
GameObject missile = (GameObject)Instantiate(bullet, transform.position, transform.rotation);
...
missile.GetComponent<FollowMissile>().enemy = temp.gameObject;
答案 1 :(得分:0)
大约5个小时后,我终于发现了这个愚蠢的错误:
public Rigidbody bullet;
应该是GameObject