Unable to Update Multiple GameObjects Together

Hello!

I’m new to Unity, but have some experience with C#.

In order to familiarize myself with Unity I’ve decided to create a simple top-down tower defense game.

Currently I’m working on the TowerController script that will allow the towers to pivot and follow enemies as they enter a given radius. I’ve figured out how to handle the triggering within a radius and have the tower rotate and face a target, however, when I have multiple towers placed in the scene they don’t respond at the same time. Currently I’m using the MousePosition as the the target for the towers. In the future I will be using other gameObjects. It appears that the towers cannot trigger at the same time. I’m not sure why this is and any feedback would be greatly appreciated.

Below is a screenshot of the scene:

47526-scene.png

Here is a screenshot of the tower GameObject:

47527-tower.png

Finally here is the TowerController.cs script that I’m using:

using UnityEngine;
using System.Collections;

public class TowerManager : MonoBehaviour {

	private bool _tracking = false;

	
	void OnMouseEnter() {
		_tracking = true;
		Debug.Log (gameObject.name + " tracking mouse");
	}

	void OnMouseExit() {
		_tracking = false;
	}

	void Update () {
		if (_tracking) {
			var mousePos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
			Quaternion rot = Quaternion.LookRotation (transform.position - mousePos, Vector3.forward);
			gameObject.transform.rotation = rot;
		}
	}
}

The mouse can only be on one object, i.e. only the “topmost” object’s OnMouseEnter is called. Its collider blocks the rest. You should probably store the target position (mouse position in this case) somewhere and then have each tower check the distance to it to determine if they are close enough to start tracking it.

I recomend you to use another aproach:

        Vector3 ownPosition = transform.position;
        ownPosition.y = 0;
        Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        mousePos.y = 0;
        float distance = Vector3.Distance(ownPosition,mousePos);
        if (distance <= range)
        {
            transform.LookAt(mousePos);
        }

This script simply calculate the distance between the tower and the mouse. (Ignoring the height(y)) If the distance is lower then the range of the tower, the tower will start to lookat the mouse.