如何从孩子到父母参考班级? [英] How to reference a class from child to parent?

查看:86
本文介绍了如何从孩子到父母参考班级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这听起来很愚蠢,但是我如何从子级的一个脚本引用父级的另一个脚本中的类呢?我在Google上找不到任何东西.注意:我的脚本中有几个错误,这不是帖子的重点.

It may sound stupid but how can i reference a class from one script in child in another script in parent? I cant find anything on google. Note: There are couple errors in my script, that's not the point of the post.

//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.

And as I told you yesterday, Add OnMouseDown() in Tile.cs and write myRenderer.material = tileDefaultMaterial; there. No need to write this in TileManager.cs. And NO need to use Raycast when using OnMouseDown().

这篇关于如何从孩子到父母参考班级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆