本文介绍了C#Unity3D中未分配的参考异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 我有一个播放器类,正在更新名为Target的Transform,而Target属于Projectile类.
  1. I have a player class where I am updating a Transform named Target and Target belongs to Projectile class.

这是我所做的,因此可以正常工作:

Here is what I did and by this it works just fine:

_pro.Target.transform.position = new Vector3(posi.x, posi.y, posi.z);  //value gets assigned to Target here
Instantiate (bulletprefab, position, Quaternion.identity);  //projectile is attached to bulletprefab so projectile gets called from here

现在,在弹丸中,尝试访问Target.transform.position时,它给出UnassignedReferenceException:弹丸的变量"Target"尚未分配.

Now, in projectile, on trying to access Target.transform.position, it gives UnassignedReferenceException : The variable 'Target' of projectile has not been assigned yet.

我已经成功地在玩家类中为Target分配了值,如何在弹丸中访问相同的值?

I successfully assigned value to Target in player class, How do I access the same value in projectile?

推荐答案

您的主要问题是,您试图在实例化包含该变量的对象之前更新变量的值.

Your main problem is that you are trying to update the value of a variable before the object that contains that variable is instantiated.

由于您的Projectile类具有对目标的引用,因此首先需要对Projectile类实例的引用.

Since your Projectile class has a reference to the target, first you need a reference to the Projectile class instance.

因此实例化您的对象,然后找到Projectile类.

So instantiate your object and then find the Projectile class.

GameObject g = Instantiate (bulletprefab, position, Quaternion.identity) as GameObject;
Projectile p = g.GetComponent<Projectile>();

然后使用新的参考来对射弹进行分配,以将值分配给目标.

Then use your new reference to projectile to assign the value to target.

p.SetTarget(target.transform.position);


您还可以使用 SendMessage 解决同一问题.


You could also use SendMessage to solve the same problem.

GameObject g = Instantiate (bulletprefab, position, Quaternion.identity) as GameObject;
g.SendMessage("SetTarget", target.transform.position);

在两种情况下,我都假定您有一个名为SetTarget的函数,该函数可让您在Projectile类中设置目标.

In both cases I assume you have a function named SetTarget that allows you to set the target in the Projectile class.

这篇关于C#Unity3D中未分配的参考异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 11:23