c# - C# Unity3D 中的未分配引用异常

标签 c# unity3d

  1. 我有一个播放器类,我正在更新一个名为 Target 的 Transform,Target 属于 Projectile 类。

这是我所做的,并且效果很好:

_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

现在,在 projectile 中,在尝试访问 Target.transform.position 时,它给出 UnassignedReferenceException :尚未分配 projectile 的变量“Target”。

我在玩家类中成功地为 Target 赋值,如何在 projectile 中访问相同的值?

最佳答案

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

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

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

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

然后使用您对 projectile 的新引用将值分配给 target。

p.SetTarget(target.transform.position);

你也可以使用 SendMessage解决同样的问题。

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

在这两种情况下,我假设您有一个名为 SetTarget 的函数,它允许您在 Projectile 类中设置目标。

关于c# - C# Unity3D 中的未分配引用异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24985545/

相关文章:

c# - .net套接字问题: client disconnect from server

c# - Azure Functions Kubernetes 找不到 local.settings.json

java - 从 Java 调用 C# dll 方法

android - Vuforia 和 Unity 1.5 不在 Android 场景中渲染对象

c# - 无法将类型 'UnityEngine.Vector2?' 隐式转换为 'UnityEngine.Vector2'

c# - 没有为类型 'System.Int64' 定义实例属性

c# - 带有排序数据的 mvc razor foreach

c# - Unity - 如何旋转和全屏视频,在 RawImage 上使用 VideoPlayer API 播放

c# - 半正弦公式Unity

c# - 统一 AdMob - ClassNotFound : com. google.unity.ads.UnityAdListener