我在游戏中使用namespace
实例化一个prefab
,但是团结一致认为prefab
不是GameObject
并返回NullReferenceException
错误
我已经正确地在保存脚本的GameObject中链接了Prefab。这是我目前在Visual Studio中拥有的代码,但是我也尝试了各种形式的代码,它们遵循的是第一行代码
public GameObject Prefab;
public void OnAppear(){
GameObject spawn = Instantiate(Prefab, Spawnpoint.position, Spawnpoint.rotation);
spawn.transform.parent = Spawnpoint.transform;}
V1
var spawn = Instantiate(Prefab, Spawnpoint.position, Spawnpoint.rotation);
V2
var spawn = Instantiate(Prefab, Spawnpoint.position, Spawnpoint.rotation) as GameObject;
整个脚本:
namespace AugReal
{
public class StartAll : MonoBehaviour
{
public Transform Spawnpoint;
public GameObject Prefab;
public void OnAppear()
{
GameObject spawn = Instantiate(Prefab, Spawnpoint.position, Spawnpoint.rotation);
spawn.transform.parent = Spawnpoint.transform;
}
public void OnDisappear()
{
Debug.Log("You lose");
}
}
}
检查器:
答案 0 :(得分:1)
请尝试以下代码:
(我还更改了属性“ Prefab”的大小写。这不会影响代码,但是标准是保留属性名称camelCase使其与PascalCased类类型区分开。)
namespace AugReal
{
public class StartAll : MonoBehaviour
{
public GameObject prefab;
public void OnAppear()
{
GameObject spawn = Instantiate(prefab, this.transform);
}
public void OnDisappear()
{
Debug.Log("You lose");
}
}
}