GameObject.Instantiate(Prefab)无效

时间:2017-09-20 00:05:38

标签: c# unity3d

问题是我不能反对。实例化,它一直给我一个错误我告诉我“嵌入式声明可能不是声明或标签声明”。

我已尝试过这些选项

var go = (GameObject)Instantiate(BuildingPrefab);
var go = Instantiate(BuildingPrefab) as GameObject;
GameObject go = Instantiate(prefab);

而且我有点新的统一所以任何建议,我做错了什么

public class FindBuildingSite : MonoBehaviour
{

public float MaxBuildDistance = 30;
public GameObject BuildingPrefab;
public PlayerSetupDefinition Info;
public Transform source;

Renderer rend;
Color Red = new Color(1, 0, 0, 0.5f);
Color Green = new Color(0, 1, 0, 0.5f);

private void Start()
{
    MouseManager.Current.enabled = false;
    rend = GetComponent<Renderer>();

}

// Update is called once per frame
void Update()
{
    var tempTarget = RtsManager.Current.ScreenPointToMapPosition(Input.mousePosition);
    if (tempTarget.HasValue == false)
        return;

    transform.position = tempTarget.Value;

    if (Vector3.Distance(transform.position, source.position) > MaxBuildDistance)
    {
        rend.material.color = Red;
        return;
    }


    if (RtsManager.Current.IsGameObejctSafeToPlace(gameObject))
    {
        rend.material.color = Green;
        if (Input.GetMouseButtonDown(0))
        var go = UnityEngine.Object.Instantiate(BuildingPrefab);
        go.transform.position = transform.position;
        go.AddComponent<Player>().Info = Info;
        Destroy(this.gameObject);
    }
    else
    {
        rend.material.color = Red;
    }


}

private object Instantiate(object prefab)
{
    throw new NotImplementedException();
}

private void OnDestroy()
{
    MouseManager.Current.enabled = true;
}
  }

1 个答案:

答案 0 :(得分:0)

此类问题通常可能是caused by its surrounding code

您的第if (Input.GetMouseButtonDown(0))行需要包含所有包含代码的括号。

当它被编译时,它实际上就是这样读的..

   if (Input.GetMouseButtonDown(0))
   {
      var go = UnityEngine.Object.Instantiate(BuildingPrefab);
   }

    go.transform.position = transform.position;
    go.AddComponent<Player>().Info = Info;
    Destroy(this.gameObject);

在if语句中没有括号,它只会读取它后面的行。

您的下一行是尝试使用go的引用,此时可能存在也可能不存在。