与(预制件)相比,GameObject []的访问性较差

时间:2018-06-29 01:30:42

标签: c# unity3d monodevelop gameobject

这基本上为我无尽的跑步者设置了瓷砖,尤其是错误:

  

可访问性不一致:字段类型'gameobject'的访问权限比tilePrefabs

enter image description here

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TileManager : MonoBehaviour {

    private Transform playerTransform;
    private float spawnZ = 0.0f;
    private float tileLength = 39.0f;
    private int amnTileOnScreen = 7;

    public GameObject[] tilePrefabs;
    // ** it is already public here **

    private List<GameObject> activeTiles;
    // Use this for initialization
    public void Start () {
        activeTiles = new List<GameObject> ();

        playerTransform = gameObject.FindGameObjectWithTag("Player").transform;
        for (int i = 0; i <= amnTileOnScreen; i++) {
            SpawnTile ();
        }
    }  

    private void Update () {
        if (playerTransform.position.z > (spawnZ - amnTileOnScreen + 
         tileLength)) {
            SpawnTile ();
            //DisableTile ();
            DestroyTile();
        }
    }

    public void SpawnTile(int prefabIndex = - 1)
    {
        GameObject go;
        go = Instantiate(tilePrefabs[0]) as GameObject;

        // reappears here

        go.transform.SetParent(transform);
        go.transform.position = Vector3.forward*spawnZ;
        spawnZ += tileLength;
        activeTiles.Add (go);
    }

    private void DestroyTile()
    {
        Destroy (transform.GetChild (0));
    }
}

1 个答案:

答案 0 :(得分:2)

问题所在的位置:

playerTransform = gameObject.FindGameObjectWithTag("Player").transform;

gameObjectGameObject之间是有区别的。注意第二个大写的“ G”。

GameObject只是用于创建GameObjects的类。

gameObject是从GameObject创建的变量,在Unity的Component类中被声明为public GameObjects gameObject。它只是GameObjects的一个实例。

gameObject脚本源自TileManager时,您可以访问MonoBehaviour变量。


FindWithTag函数在GameObject类中,并且也声明为static,这意味着您不需要GameObject实例来调用它。您必须使用类名

直接调用它

替换

gameObject.FindGameObjectWithTag("Player").transform;

使用

GameObject.FindGameObjectWithTag("Player").transform;