无法将类型"UnityEngine.GameObject"隐式转换为"GameMaster"?



我的脚本中有这个错误,我已经查看了其他有同样问题的线程,但没有一个解决方案对我有效。

这是我的脚本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameMaster : MonoBehaviour {
public static GameMaster gm;
void Start() {
if (gm == null)
gm = GameObject.FindWithTag("GM");
}

public Transform PlayerPrefab;
public Transform SpawnPoint;
public void RespawnPlayer () {
Instantiate (PlayerPrefab, SpawnPoint.position, SpawnPoint.rotation);
}
public static void KillPlayer(Player player) {
Destroy (player.gameObject);
gm.RespawnPlayer();
}
}

您需要将不同类型的所有对象强制转换为给定类型(假设可以是此给定类型(

Boo Foo = (Boo)GetMyObject();
public Poo GetMyObject()...

在这种情况下(假设GameMaster是MonoBehavior(,您无法进行这样的转换。您需要在GameObject上使用GetComponent方法。

void Start() 
{
if (gm == null)
gm = GameObject.FindWithTag("GM").GetComponent<GameMaster>();
}

最新更新