Rookie
Rookie

Reputation: 193

Unity How to check if a child object has a certain script or is a certain type

I'm working on a tower defense game. I have towers as child objects of tiles. I need to check if a certain tower is on a certain tile. What I'm currently doing is this:

Tiles[new Point(currentPos.X, currentPos.Y)].transform.GetChild(0).GetComponent<Tower>() is IfStat)

IfStat is a class derived from tower. But this returns false. How can I check is the tower -child- has IfStat on it as the script?

Thanks.

Upvotes: 0

Views: 3307

Answers (2)

bashis
bashis

Reputation: 1243

Does this do the job?

var ifstat = Tiles[new Point(currentPos.X, currentPos.Y)].transform.GetComponentInChildren<IfStat>();
if (ifstat != null)
{
    //Do whatever you wish with ifstat
}

Upvotes: 0

TehTris
TehTris

Reputation: 3217

Assuming:

Tile is a GameObject with tile_script.cs attached to it.

Tower is a GameObject with tower_script.cs attached to it, and is a Child of TILE ( ie in hierarchy, its underneath the > icon of it )

Inside tile_script.cs you would get the tower_script by doing

tower_script script = gameObject.getComponentInChildren<tower_script>()

If you want to verify its existence, check it against null like if (script != null) ... which simplifies to if (script) or change to the plural version getComponentsInChildren and check if (script.Length >= 1) or something like that.

Upvotes: 1

Related Questions