如何从小孩到父母引用一个类?
这可能听起来很愚蠢,但我怎么能从父母的另一个脚本中的孩子的一个脚本中引用一个类?我无法在谷歌上找到任何东西。注意:我的脚本中有几个错误,这不是帖子的要点。如何从小孩到父母引用一个类?
//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;
}
}
有一句名言:
var allTiles = transform.GetComponentsInChildren<Tile>();
正如我昨天跟你说,在Tile.cs添加OnMouseDown()
,写myRenderer.material = tileDefaultMaterial;
有。无需在TileManager.cs中编写它。当使用OnMouseDown()
时,不需要使用Raycast
。
我试过让我的代码在Tile.cs中,但我无法管理像tileIsSelected或selectedTileGroup这样的事情,因为我的所有瓷砖都有这个脚本。例如,如果我选择一个瓷砖,然后点击空白空间,我希望tileIsSelected在所有瓷砖上都是假的,或者当我点击组编号为1的瓷砖时,我想更改所有瓷砖上具有相同组编号的材质。我的事情应该更容易做到这一点,如果我有TileManager.cs中的代码。 – N1ckGreek
现在有道理。 –
base.Method怎么样?
应该这样做
帕特里克霍夫曼不编辑我的答案无用的编辑。谢谢。 –
我不认为这是一个继承问题 - 他谈论的是Unity变换层次结构中的父/子关系。 – Serlite
我看不懂你的形象代码,所以我会弥补我自己的类名的例子。我会打电话给父级TileManager
和子级Tile
。
说在Tile
你想访问TileManager
瓷砖阵列。如果allTiles
被宣布为公开,您可以在Tile
的某个地方执行。
TileManager tileManager = transform.parent.GetComponent<TileManager>();
var allTiles = tileManager.allTiles;
现在Tile
孩子有一个对数组的引用。这是你想要的吗?
你不能那样做。你的班级已经从MonoBehaviour继承。 你想要达到什么目的? –
请不要提供代码作为图像。请参阅http://meta.*.com/questions/303812/discourage-screenshots-of-code-and-errors – gus27
我想创建一个类,并为每个tile创建一些变量,然后通过管理脚本管理它们。我不确定这是否是最好的方式。我是C#和Unity的新手。 – N1ckGreek