Hello. This is my script for a the hill (as in king of the hill) type area in my game. In it, I check to see if the player object is within a certain distance of the hill object, if it is then I activate the player's weapons. It works fine, until I try to instantiate multiple clones of the hill. It only registers for the newest hill spawned, how can I make it so that if the player is within a set distance of any of the instantiated hills "weapon" variable is changed?
var player : Transform;
function Update () {
var distance = Vector3.Distance(player.position, transform.position);
if (distance > 10.0f) {Hotspot_W.weapon=0;}
if (distance < 10.0f) {Hotspot_W.weapon=1;}
}
As long as you had this script on each hill, the weapon variable would be changed for each. The problem is, only the last one would count. There's no telling what order various Update()s will run in, so you have to work around that. Here are examples of what you actually could use. You'd attach this script to any game object you want, and keep its hills variable updated as you create and destroy hills. I don't know what you called your script, so I'll just call it Hill.
Here's with List.Exists():
import System.Collections.Generic;
var hills : List.<Hill>;
var weapon1SqrDistance = 100;
function Update () {
if (hills.Exists(function(hill) {
(player.position - hill.transform.position).sqrMagnitude < weapon1SqrDistance;})
) Hotspot_W.weapon = 1;
else Hotspot_W.weapon = 0;
}
...and here's the same thing done with a loop.
var hills : List.<Hill>;
var weapon1SqrDistance = 100;
function Update () {
Hotspot_W.weapon = 0;
for (var i = 0; i < hills.Count; ++i)
if ((player.position - hills*.transform.position).sqrMagnitude < weapon1SqrDistance) {*
*Hotspot_W.weapon = 1;*
*break;*
*}*
*}*
*```*
*<p>Note that in each case, I compared square distances, because taking the square root for distance comparisons is unnecessary. It makes for a less easy-to-use weapon1SqrDistance variable though, so you decide on ease vs. performance.</p>*