Instantiating objects too fast at the same location causes problem

It’s an rts game, whenever I right click I instantiate an object to indicate the target location the player is moving to. The newly instantiated object does a very short animation for about 0.5 seconds and then destroys itself.

It’s running smoothly unless I spam right click on the same location. This means that I am now actually clicking on the “target indicator object”, because I click more than once every 0.5sec which is the animation time before object is destroyed.

This causes the indicator object to seem like it’s growing bigger and bigger for each mouse click, until it doesn’t fit the screen anymore. Then it becomes normal size and starts all over again from normal size.

In the scene view it looks more like it’s moving closer and closer to the camera for each click, until it is out of camera sight.

So how do I fix this problem?

This is where I instantiate the object, I don’t believe this is where the mistake is, but take a look please:

				if(Input.GetMouseButtonDown(1)) {
                    GameObject newPosition = GameObject.Find("RightClickTarget");
                    newPosition.transform.position = hit.point; // hit = RaycastHit
                    DestroyObject(GameObject.Find("Target Instantiated")); // If indicator already exists, delete the last one
					GameObject targetObj = Instantiate(target, hit.point, Quaternion.identity) as GameObject; // This is the indicator object
					targetObj.name = "Target Instantiated"; 
				}

Maybe it is because of the animation? When the target is instantiated, it moves a few steps up in the Y-direction, then sinks down below the terrain and destroys itself.

Or is it because I don’t use layermasks? Don’t know much about how to use them, but maybe I can put the instantiated object in a layer that is ignored by the
RaycastHit hit ?

Don’t do that. Instantiating something that destroys itself a second later is bad practice in every situation. Instantiate and Destroy are two of the slowest things Unity does, and doing it all the time will lag your game.

Have it already existing but inactive, then move it to the click position, activate it, and play its animation. The animation can deactivate the object when it is done by way of a script event. Get in the habit of using SetActive instead.

You should not be able to click the move target indicator in any case. It does not need to have a collider on it. Take off the collider, and that solves the other part of your problem.

In my game, each unit has its own move target, and they are all parented to an empty holder gameobject. The script on the cursor creates one and assigns it to a variable on the unit’s script the first time it is given a move order if that unit does not have one yet.