【问题标题】:Error "Object reference not set to an instance of an object" when dealing with prefab处理预制件时出现错误“对象引用未设置为对象的实例”
【发布时间】:2019-10-30 17:20:29
【问题描述】:

我试图让相机跟随我的播放器(从预制件实例化),但我的相机脚本中不断出现错误。

我的相机脚本(错误在offset = transform.position - Game.currentPlayer.transform.position;行):

public class CameraControl : MonoBehaviour
{
    private Vector3 offset;

    private void Awake()
    {
        offset = transform.position - Game.currentPlayer.transform.position;
    }

    void LateUpdate()
    {
        transform.position = Game.currentPlayer.transform.position + offset;
    }
}

我在这里设置了我的currentPlayer 变量:

void Start()
    {
        GameObject newPlayer = Instantiate(player,transform.position,transform.rotation);
        newPlayer.name = "Player";
        currentPlayer = newPlayer;
    }

如果您需要更多脚本来提供帮助,请询问 :)

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    AwakeStart 之前被调用。实际上,即使是 all Awake 方法也已完成第一个 Start 被调用(另见 Order of Execution for Event Functions)。

    因此,Awake 中尚未设置引用。

    您必须将其移至 Start 方法或将实例化部分移至 Awake

    在这两种情况下,仍然不能保证Game 脚本将在GameControl 之前执行其Start。因此,您仍然需要调整Script Execution Order,从而使Game 始终在GameControl 之前执行。简单的

    • 打开编辑 > 项目设置 > 脚本执行顺序
    • Game 脚本中拖放到DefaultTime 块之前
    • 也可选择对现有项目进行分类

    您也可以使用事件系统:

    public class Game : MonoBehaviour
    {
        public static event Action OnInitilalized;
    
        public static GameObject currentPlayer;
    
        privtae void Start()
        {
            GameObject newPlayer = Instantiate(player,transform.position,transform.rotation);
            newPlayer.name = "Player";
            currentPlayer = newPlayer;
    
            OnInitilalized?.Invoke();
        }
    }
    

    然后在GameControl 中添加回调到OnInitialized 事件,如

    private void Awake()
    {
        // This makes sure the callback is added only once
        Game.OnInitialized -= OnGameInitialized;
        Game.OnInitialized += OnGameInitialized;
    }
    
    private void OnDestroy()
    {
        // always make sure to remove callbacks if no longer needed
        Game.OnInitialized -= OnGameInitialized;
    }
    
    privtae void OnGameInitialized()
    {
        offset = transform.position - Game.currentPlayer.transform.position;
    }
    

    【讨论】:

      猜你喜欢
      • 2014-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-09
      • 2012-08-31
      • 2011-11-21
      • 2012-10-01
      • 1970-01-01
      相关资源
      最近更新 更多