Problem using the same script for different objects

Hello there, I’m new at unity and I’m having troubles with the scripts. I know this should have a simple solution but I couldn’t find a solution that fits to my problem.

I have a GameObjects that actives a trigger and active an animation when the player reach its collider, that works fine, the problem is that I have another object with the same script because I want it to do the same. Those two objects share the animator and the script because they do basicaly the same, the problem is that when the player reach the first collider, both objects starts its animation. I need a lot of this objects and I don’t want to do a script or an animator for every single one, but I don’t undertand why the collider of one objects triggers the animation of the other object.

They are not related in the hierarchy and I’m not using static variables, please help me to solve this.

This is the code:

//---------------------------------------------------------------------------------
TriggerDialogos Trigger;
Animator Anim;
public GameObject CalzonSiguiente;

void Start()
{
Anim = GetComponent();
Trigger = GetComponent();
}

void OnTriggerEnter2D(Collider2D other)
{
Trigger.ActivarDialogo();
Anim.SetTrigger(“Desaparecer”);
if (CalzonSiguiente != null)
{
CalzonSiguiente.SetActive(true);
}
}

Inside this function:

OnTriggerEnter2D(Collider2D other)

print the name of this GameObject:

Debug.Log("OnTriggerEnter2D(Collider2D other): I am " + name);

So you can see what is triggering what and when.

You could also print the name of the CalzonSiguiente, which sounds absolutely delicious.

Also, please use code tags: Using code tags properly

Generally to solve this sort of thing, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run?
  • what are the values of the variables involved? Are they initialized?

Knowing this information will help you reason about the behavior you are seeing.

1 Like