Same script on multiple gameobjects

Hi,

In my scene I have several cube gameobjects and they all have the same script attached as compononent :

Cube - Script1

Cube - Script1

Cube - Script1

During runtime, if I click on a cube which is colliding with another, a fixed joint is created and both cubes are attached together. The problem is the other cubes on the scene also react to the code and attach themselves. How can I prevent that ? I just want the cube that has been clicked on to attach to the one it’s colliding with and not the others.

Thanks!

Here’s my script :

public class JointScript : MonoBehaviour {
	
	RaycastHit hit;
	int maxBuildDist = 10;
	int hasJoint = 0;
	private bool touched = false;

	void Update()
	{
		if(Physics.Raycast(Camera.main.ScreenPointToRay(new Vector3((Screen.width / 2), (Screen.height / 2), 0)), out hit, maxBuildDist))
		{
			if(hit.transform.tag == "piece")
			{
				if(Input.GetMouseButtonDown(1))
				touched = true;
			}
		}
	}
	
	void OnCollisionStay(Collision collision) 
	{ 

			if(touched)
			{
				var joint = gameObject.AddComponent<FixedJoint>(); 
				joint.connectedBody = collision.rigidbody; 
				joint.enableCollision = true;
				touched = false;
				
			}
		

	}
}

It appears that you want only the clicked object sets touched to true while currently if an object is clicked all the cubes set touched to true.

Given your current setup, the easiest way to do this would be to change the line
if(hit.transform.tag == “piece”) to if(hit.transform==transform).

A better way would be to make a new gameObject with the update script so only one raycast is done per update then use hit.collider.transform.GetComponent().touched=true.

When you get the transform via Raycast, use GetComponent to find a reference to your rotation script and call the appropriated method.

Something like this should work…
if(Physics.Raycast(ray, out hit, maxBuildDist)) {
if(hit.transform.tag==“piece”) {
hit.transform.GetComponent().Rotate();
}
}

You can just at a bool to activate the cube that has been clicked,

OnCollisionEnter(Collision col){
if(isActive == false){
return;
}
}

void OnClicked(){
isActive = true;
}

void SomeEventOrTimePassed(){
isActive = false;
}

edit: which appears that you already have, but the only way you are turning it off is if the cube collides with another. If I click on a cube and it does not perform the arm action, its still active and once it collides with one that was clicked on last it would also create the joint.