Make so the script only moves and makes actions to the gameObject that its attached to.

Hello having a major problem, i’ve developed a script that can select, deselect and move a worker or hero. But if i spawn more than one in the scene then all the different workers will do the same order, even if THEY are not told to. Is there a way of fixing this? Thanks :slight_smile:

here is my worker Controller

(worker and hero is the same thing)
Dont think you will need the move to mousecursor position,

#pragma strict

var SelectedRing : GameObject;
var Selected : boolean = false;

var showGUI : boolean = false;

var WorkerSpawn : GameObject;
var Hero : GameObject;

var lastHit: GameObject; // Keep track of last object clicked



function Update ()
 {
  //Selects Worker && Deselects worker
  var ray: Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
  var hit : RaycastHit;
  
  	if(Input.GetMouseButtonDown(0))
 	 {
     	if (Physics.Raycast(ray,hit) && hit.transform.gameObject == Hero)
     	{
       	  	  Selected = true;
        	  SelectedRing.SetActive(true);
     	}
     	 else
     	{
          	Selected = false;
          	SelectedRing.SetActive(false);
     	}
  	}
  	
  	//ShortKey To spawn other worker
  	if(Input.GetKeyDown(KeyCode.Q))
  	{
  		showGUI = true;
  	}
  	
  	//Instant Stop Any Movement
  	if(Input.GetKeyDown(KeyCode.Space))
  	{
  		Hero.transform.position = transform.localPosition;
  	}
 }

function Start ()
{
	SelectedRing.SetActive(false);
}

is this script attached to each worker/hero?

also can you show the code where you give an order?

also for optimization you should put
var ray: Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
var hit : RaycastHit;

inside the bracket of that condition if(Input.GetMouseButtonDown(0))

so you only calculate the raycasting if there is a click

Do not attach the script to each Hero/Worker as it will cause the game click test (and raycast) to be executed for each Hero/Worker (e.g. if you have 100 heroes the raycast/click test will be executed 100 times per update! which will be inefficient).

Instead attach the controller script to a single game object and use a tag to detect which object has been hit:

if (Physics.Raycast(ray,hit) && (hit.transform.gameObject.CompareTag("Hero") || hit.transform.gameObject.CompareTag("Worker") ) 

EDIT:
If you want the ring to appear on each clicked hero/worker then attach the ring object under the hero/worker game object (in the hierarchy) and disable it by default.
In the hero/worker script declare a public member to hold a reference to a ring prefab and
when a hero/worker is selected extract the selected game object and enable the ring game object:

if (Physics.Raycast(ray,hit) && (hit.transform.gameObject.CompareTag("Hero") || hit.transform.gameObject.CompareTag("Worker") )  {
     HeroScript heroScript = hit.transform.gameObject.GetComponent<HeroScript>();
     heroScript.ring.SetActive(true);
}