how to communucate GameObject and Script by tag?
Hi Guyss... iam newbie here and i have a question here, can i communucate GameObject and Script by tag?
for example :
1 Cube (Player)
5 Cube (Enemys)
in Player Cube, i put Movement Script and for Enemys Cube, i also put Movement Script too. But, when player cube detect collision with enemys cube, i want 5 enemys cube disable their the Movement Script.
for disable movement script in enemys cube, i make one script and i call it Player_Collusion and i put this script into player cube, in this script i will control all enemys Movement script.
Hope you guys will understand what i mean. Iam sorry for Bad Grammar ^^
Thanks
Answer by Sgt_Spike · Aug 17, 2018 at 05:38 PM
Hey there. So from what I'm understanding you have two scripts, 'Movement', and 'Player_Collision'. Movement is attached to the player and the five enemies while 'Player_Collision' is attached to the player. Then the 'Player_Collision' script is used to disable the script 'Movement' for the enemies, right?
I think putting this code in your 'Player_Collision' script should do the trick...
private void OnTriggerEnter(Collider col)
{
if (col.tag == "Enemy")
{
GameObject[] enemies= GameObject.FindGameObjectsWithTag("Enemy");
foreach(GameObject enemy in enemies)
{
enemy.GetComponent<Movement>().enabled = false;
}
}
}
So when a collision is detected and the collided object with the player is tagged as 'Enemy' (Make sure you change 'Enemy' to whatever you have tagged the enemies as), Unity will then find all the active gameobjects in your scene also tagged as 'Enemy' and then the 'Movement' script will be disabled for each of them.
Also, remember to tick the 'Is Trigger' box for all of your enemy colliders within the editor.
Good Luck :D