【问题标题】:Unity - Start Method not runningUnity - 启动方法未运行
【发布时间】:2019-11-01 17:11:29
【问题描述】:

我是 Unity 的新手,我正在学习一个飞扬的小鸟教程,以更加熟悉游戏引擎。我正在关注 CodeMonkey 教程。我在游戏结束屏幕。这是我附加到我的 GameOverWindow 的脚本。但只有 Awake() 被调用。开始没有。因此,我的活动无法正常工作,因此不会显示游戏结束窗口。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using CodeMonkey.Utils;

public class GameOverWindow : MonoBehaviour
{
    private Text scoreText;
    // Start is called before the first frame update
    private void Start()
    {
        Bird.GetInstance().OnDied += Bird_OnDied;
    }

    private void Awake()
    {
        scoreText = transform.Find("scoreText").GetComponent<Text>();

        transform.Find("retryBtn").GetComponent<Button_UI>().ClickFunc = () => { UnityEngine.SceneManagement.SceneManager.LoadScene("GameScene"); };
        Hide();
    }

    private void Bird_OnDied(object sender, System.EventArgs e)
    {
        scoreText.text = Level.GetInstance().GetPipesPassedCount().ToString();
        Show();
    }

    // Update is called once per frame
   private void Update()
    {

    }

    private void Hide()
    {
        gameObject.SetActive(false);
    }
    private void Show()
    {
        gameObject.SetActive(true);
    }
}

【问题讨论】:

  • 你确定 Start() 不起作用,而不是事件本身的代码?
  • @Frytek 是的。我使用 Visual Studio 进行调试,但它从未启动。我将断点放在 Start() 的开头

标签: c# .net unity3d flappy-bird-clone


【解决方案1】:

根据Unity docs

Start 在脚本的生命周期中只被调用一次。但是,在初始化脚本对象时会调用 Awake,无论脚本是否启用。如果在初始化时未启用脚本,则可能不会在与 Awake 相同的帧上调用 Start。

因此,如果从一开始就禁用了 GameOverWindow,则不会执行 Start,但会执行 Awake。您可以将事件初始化移至 Awake,它应该可以工作(只要添加事件是问题,而不是事件中的代码)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-07
    • 2020-10-07
    • 1970-01-01
    • 2021-12-07
    • 2023-01-25
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多