Raycast trigger multiple script at the same time

Hello,

have a few question here. Have a problem with my script. I’m making a Physic.Raycast script to press a multiple 3d object with my mouse. All the 3d object will have the same script and same tag. But the problem now is, When I press one off the 3d object the script does work, but it trigger every script in the other 3d object, How do I prevent only the 3d object that I press trigger the script not the others.

here is my full script :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FlipIcon : MonoBehaviour
{
    public float fRandomMoveMin;
    public float fRandomMoveMax;
    float fRandomMove;
    float fRandomTimer;

    public Animator aFlip;
    public bool isFlip;

    public GameObject goTrigHex;

    public bool isOpen;

    [Header("InputTouch")]
    RaycastHit rcHit;
    Ray rRay;

    // Start is called before the first frame update
    void Start()
    {
        fRandomMove = Random.Range(5f, 10f);             
    }

    // Update is called once per frame
    void Update()
    {
        rRay = Camera.main.ScreenPointToRay(Input.mousePosition);

        if (Physics.Raycast(rRay, out rcHit, 100))
        {
            if (rcHit.collider.gameObject.CompareTag("BtnFlip"))
            {
                if (Input.GetMouseButton(0))
                {
                    isOpen = true;
                }
            }
        }

        Flip();
    }

    public void Flip()
    {
        if (isOpen)
        {
            aFlip.SetTrigger("FlipOpen");
            goTrigHex.SetActive(false);
        }
        else
        {
            if (!isFlip)
            {
                fRandomTimer += Time.deltaTime;

                if (fRandomTimer >= fRandomMove)
                {
                    aFlip.SetTrigger("FlipRandom");
                    fRandomMove = Random.Range(5f, 10f);
                    fRandomTimer = 0.0f;
                }
            }
            else
            {
                aFlip.SetTrigger("FlipClose");
                aFlip.ResetTrigger("FlipOpen");
            }
        }
    }

    public void FlipOpen (bool isFlipOpen)
    {
        isOpen = isFlipOpen;
    }

    public void FlipClose (bool isFlipClose)
    {
        isFlip = isFlipClose;
    }
}

Here I put a video of whats happening to my script and object :

You have every FlipIcon running the same code in Update():

  • uses the global mouse position
  • casts into the scene
  • asks if the tag is “BtnFlip”
  • checks the same click button

So of course they all act the same.

The general pattern you want is have ONE thing (perhaps a click manager or something?) that casts into the scene ONCE and then observes what it hits, sees if it is a “BtnFlip” or whatever, and tells the thing that it hits what to do.