我正在制作一个游戏系统,玩家使用吊索,当他击中目标并摧毁它时,他会得到分数,但我无法将不同的脚本转换为游戏对象。 通过获取组件。
我过去遇到过这个问题,更改 FindGameObjectsWithTag 早些时候帮助了它,但现在它没有,我仍然不明白为什么会发生这种情况,因为在我重新启动 Unity 一次并再次编写整个项目后,它工作得很好。 但这次我不想这样做。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameController : MonoBehaviour
{
public int Score { get; private set; }
public Text ScoreText;
private static GameController _instance;
public static GameController Instance
{
get
{
if(_instance == null)
{
var obj = GameObject.FindWithTag("GameController");
if (obj != null)
{
_instance = obj.GetComponent<SlingBackController>();
}
}
return _instance;
}
set
{
_instance = value;
}
}
void Awake()
{
Instance = this;
}
void Start()
{
Score = 0;
}
public void AddToScore(int points)
{
if(points >0)
{
Score += points;
ScoreText.text = Score.ToString();
}
}
}
错误位于此行: _instance = obj。GetComponent();
它应该工作得很好,没有问题,但显然它有,我不太了解它们。
将private static GameController _instance;
更改为private static SlingBackController _instance;
问题是计算机需要一个游戏控制器,但你在这里_instance = obj.GetComponent<SlingBackController>();
分配了一个SlingBackController,这不起作用。
您正在尝试将SlingBackController
引用分配给类型为GameController
的字段。
如前所述,您似乎只是将代码从SlingBackController
复制到您的GameController
中,但忘记相应地排除GetComponent
的类型。
它应该是
public static GameController Instance
{
get
{
if(!_instance)
{
var obj = GameObject.FindWithTag("GameController");
if (obj)
{
_instance = obj.GetComponent<GameController>();
}
}
return _instance;
}
private set
{
_instance = value;
}
}
或者更有效的使用FindObjectOfType
public static GameController Instance
{
get
{
if(!_instance) _instance = FindObjectOfType<GameController>();
return _instance;
}
private set
{
_instance = value;
}
}
然而,这就是所谓的"延迟初始化",这意味着它只在需要时完成。
由于您无论如何都在Awake
中设置值,因此您实际上应该简单地确保在Start
方法之前没有类依赖于Instance
。
我的黄金法则通常是:
- 使用
Awake
初始化类自身的值和GetComponent
调用。 - 每当类依赖于首先初始化的另一个类值时,请使用
Start
。
有时这是不可能的,那么您可以使用脚本执行顺序设置来配置脚本的执行顺序,或者作为回退使用代码进行延迟初始化。