Kevin Jensen Petersen
Kevin Jensen Petersen

Reputation: 513

Accessing a script on all objects with tag in Unity

My question is simple, how to access my gameobjects custom C# script through a foreach.

I've tried following:

foreach(TowerController go in GameObject.FindGameObjectsWithTag("Tower")) {
        go.upgradeTowerProgress = false;    
    }

Doesn't seems to work. Dunno why, that's why im here to ask! xD

TowerController is my custom script on the gameObjects with tag Tower.

Upvotes: 4

Views: 7088

Answers (1)

CC Inc
CC Inc

Reputation: 5918

This should work (untested):

foreach(GameObject go in GameObject.FindGameObjectsWithTag("Tower")) {
        go.GetComponent<TowerController>().upgradeTowerProgress = false;    
    }

What I changed is that you are iterating a GameObject array, so you need to do foreach(GameObject go..., then you use the GetComponent function to get the component that is of the type TowerController and then you can access its updateTowerProgress. THIS page is always a good reference.

Upvotes: 6

Related Questions