How to interact with multiple instances of a single prefab?

I’m still learning Unity but this has got me stumped and I’m not finding any clues to fix it (mostly because I’m not sure what terms to even search for). I’ve been trying to make a simple metal detector - the user drags a paddle around the screen and when it nears a prefab called ‘treasure’ an audio sound beeps faster. So far so good but as soon as I duplicate the treasure prefab only the most recent instance of it works, the older and original ones just stop working.

public Transform detector; // The metal detector
public Transform treasure; // The treasure
public AudioSource beepSound; // The "speaker" that plays the sound
public AudioClip Beep; // The sound file itself

void Start() {
	beepSound.PlayOneShot(Beep);

}

void Update() {

	float dist = Vector3.Distance(treasure.position, detector.position); // Measure between the treasure and the detector and save it as dist

	if (dist > 0 & dist < 1) { // If less than 1 away from treasure
		if (beepSound.isPlaying == false) { // If the beep isn't currently playing
			beepSound.Play(); // Play the beep	
		}
	}
}

The treasure prefab has the user’s paddle, the audiosource, the beep sound and itself dragged onto it’s public variables in the inspector. This has to be a serious newbie question but I’m hoping a prod in the right direction can help me.

Is your engine a separate mesh? In your modelling program, make sure that your model's centre is placed exactly on the origin (if you are using Blender, this is Shift+Alt+Ctrl+C)

1 Answer

1

The better way to do it is as @Mmmpies says, but if you want to keep it this way :

change
public Transform treasure
to
public Transform[] treasures and fiill it with all the treasure transforms
then in your Update() function check the distance to all treasures transforms :

for (int i = 0; i < treasures.size(); i++)
{
 // check the distance for treasures

}

Cool thanks for the reply, I was aiming at keeping it as close to how I'd started but like you guys said it might not be the best way.