这可能听起来很愚蠢,但我如何从父母的另一个脚本中的一个脚本引用一个类?我在谷歌上找不到任何东西。注意:我的脚本中有几个错误,这不是帖子的重点。
//Public
//Private
private Rigidbody myRigidbody;
private Renderer myRenderer;
private Material tileDefaultMaterial;
private Material tileSelectedMaterial;
private Material tileSameGroupMaterial;
void Start () {
myRigidbody = GetComponent<Rigidbody> ();
myRenderer = GetComponent<Renderer> ();
tileDefaultMaterial = Resources.Load ("TileDefault", typeof(Material)) as Material;
tileSelectedMaterial = Resources.Load ("TileSelected", typeof(Material)) as Material;
tileSameGroupMaterial = Resources.Load ("TileSameGroup", typeof(Material)) as Material;
}
void Update () {
}
public class TileClass {
public int tileGroup = 0; //Indicates the Tile Group Number.
}
//Public
public GameObject[] allTiles; //Aray of all Tile GameObject.
public bool tileIsSelected = false; //If a Tile is Selected.
public int selectedTileGroup = 0; //Indicates the Selected Tile Group Number.
public int tileGroup = 0; //Indicates the Tile Group Number.
//Private
void Start () {
allTiles = new GameObject[transform.childCount];
for(int i = 0; i < transform.childCount; i++){
allTiles [i] = transform.GetChild (i).gameObject;
}
}
void Update () {
}
void OnMouseDown (){
RaycastHit hitInfo = new RaycastHit ();
bool hit = Physics.Raycast (Camera.main.ScreenPointToRay (Input.mousePosition), out hitInfo);
if (hitInfo.transform.gameObject.tag == "Tile" && tileIsSelected == false) {
Debug.Log ("A Tile is Selected!");
tileIsSelected = true;
selectedTileGroup = ;
for(int i = 0; i < allTiles.Length; i++){
if (this.tileGroup == selectedTileGroup) {
allTiles [i].GetComponent<Renderer> ().material = tileSameGroupMaterial;
}
}
myRenderer.material = tileSelectedMaterial;
} else if (hitInfo.transform.gameObject.tag == "Tile" && tileIsSelected == true) {
Debug.Log ("Second Tile is Clicked! (Should Swap them!)");
myRenderer.material = tileDefaultMaterial;
}
}
答案 0 :(得分:4)
有一句名言:
var allTiles = transform.GetComponentsInChildren<Tile>();
正如我昨天告诉你的那样,在Tile.cs中添加OnMouseDown()
并在那里写myRenderer.material = tileDefaultMaterial;
。无需在TileManager.cs中编写此代码。使用Raycast
时无需使用OnMouseDown()
。
答案 1 :(得分:1)
我无法读取您的图片代码,因此我将为该示例构建自己的类名。我将调用父类TileManager
和子类Tile
。
在Tile
中说您希望访问TileManager
中的图块数组。如果将allTiles
声明为公开,则可以在某处Tile
进行。
TileManager tileManager = transform.parent.GetComponent<TileManager>();
var allTiles = tileManager.allTiles;
现在Tile
子项具有对数组的引用。这是你想要的吗?
答案 2 :(得分:-4)
base.Method怎么样?
应该这样做