Accessing a GameObject parent Object

Hello there, quite new with Unity but experienced in Javascript :slight_smile:

I have a question that I can’t seem to answer by myself so I come to you in hope to get one :slight_smile:

I am creating a Tile-based game with much informations attached to each tiles, so I created a Tile class with my properties into it, and in those properties there is a sprite property which is containing a GameObject ( and its meshes, colliders, etc… ). I use raycasting to click on my tiles and get back which one was clicked, but i want to access the Tile object with all the properties attached. I can’t seem to get to it. I tried




( and also with parent instead of root ) and it always seem to stop to the Plane primitive not going back further to the sprite property and the Tile object.

Here is my code so you can understand :

class Tile extends System.Object{
	var sprite : GameObject = GameObject.CreatePrimitive(PrimitiveType.Plane);
	var type : String = "Tile" ;
	var allegiance : String = "Neutral" ;
	function Tile(xc:int, zc:int, ox:int, oz: int){
		this.sprite.transform.localScale.x *= .1 ;
		this.sprite.transform.localScale.z *= .1 ;
		this.sprite.transform.position = Vector3(ox + xc, 0, oz + zc);
		this.sprite.renderer.material.color = Color.white ;
		this.sprite.renderer.material.shader = Shader.Find("Self-Illumin/Diffuse");

    var hit : RaycastHit;
	var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
	if( Physics.Raycast(ray, hit, 5000.0) ){

        // This actually is the correct Tile.sprite gameObject selected here
		var select : GameObject = hit.collider.gameObject ; 

		select.transform.tag = "selected" ;
		originalSelectedObjectColor = select.renderer.material.color ;

        // This correctly colors my tile in red
		select.renderer.material.color = ;

        // This get me "Plane"

		if( select.GetType() == "Plane" ){
			createTower(aPlayers[0], hit.collider.transform.position.x, hit.collider.transform.position.z);

Any idea on how to do this ? Thanks a lot.

Assuming i understand what your asking its really straight forward:


If there is something you cannot answer I suggest google be your first port of call for these simple matters (:

The typical code I see handles what you are doing a bit differently. Your Tile class would be derived from Monobehaviour. Then you would add it as a component (GameObject.AddComponent()) to the game object you create. To get access to the tile data you would use GameObject.GetComponent().

There may be good reasons for you to dynamically create your tiles, but in the couple of tile/card games I’ve written, I use a tile prefab. That is I create a single tile with a tile script as a prefab and use Instantiate() to create the many instances of the tiles at runtime.

Now with the Tile component attached to the game object, you would do something like:

var tile = select.GetComponent(Tile);