简体   繁体   中英

Using 1 script to assign different values based on tags - C# - Unity

I am making a Game on Unity 3D. I have 1 script which i am using on 2 different characters(prefabs)

So I have this variable called Target

public Transform Target;

This script is passed on Hero and vilain both. I want script to get Hero as target for villain and villain as target for hero. Maybe I can do it with tags??

Help would be appreciated.

You can do something like this

if(Target.tag == "Hero"){
//hero Detected
}

or

if(Target.tag == "Villan"){
//Villan Detected
}

Suppose you have a script, attached to both (Hero and Villan)

 class xyz: MonoBehaviour{
    public Transform Target;
    void Start(){
         if(this.tag == "Villan"){
              //Villan Detected, assign hero
         }
         else if(this.tag == "Hero"){
             //Hero Detected, assign Villan
        }
   }
}

So i found the solution, pretty simple but took me a whole day to figure out lol.

GameObject[] protagonistOpponent = GameObject.FindGameObjectsWithTag("Player");
        foreach (GameObject obst in protagonistOpponent)
            obst.GetComponent<User_Stats>().Target = FKManage.Enemy.transform;

        GameObject[] AntagonistOpponent = GameObject.FindGameObjectsWithTag("Enemy");
        foreach (GameObject obst in AntagonistOpponent)
            obst.GetComponent<User_Stats>().Target = FKManage.LocalPlayer.transform;

Thank you all who tried helping me :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM