c# - 为什么我不能将一个游戏对象分配给另一个游戏对象的公共(public)变量

标签 c# unity-game-engine

这是玩家脚本中的方法,它捕获光标下的敌人并创建一个导弹来跟踪它。

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/

相关文章:

ios - Unity Facebook 插件在登录后终止应用程序(iOS)

c# - 调试不起作用

c# - 按住按钮时播放声音

c# - 用于全文搜索的索引数据库,Lucene/iFiler/SQL FTS/..etc

c# - 数据库与资源

c# - TypeDescriptor.GetConverter(typeof(string)) 无法转换为我的自定义类型

c# - Awake() 用于没有实例化的预制件

c# - 使用 HtmlHelper DisplayFor 的字符串值 "Boolean"问题

c# - "Build"构建我的项目,"Build Solution"没有

linux - 在 Headless Linux 上运行 Unity CLI 构建开源项目 - 许可证问题