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.
There are ways of recording individual prefabs, you could change the name when you instantiate or add a script that holds a variable to identify it but you don't really need that for your example.
What you need it a collider set as a trigger on your prefab. Scale it so when the detector passes through it you call the code using OnCollisionEnter(Collider other).
You want to tick is trigger so the collider doesn't collide it just registers when something goes through it. You can also name or tag your detector so it can tell the difference between your detector and some other gameObject hitting the collider.
void OnCollisonEnter(Collider other)
{
if (other.tag == "Detector")
{
// put your beep code here
}
}
note that code is for 3D, 2D has it's own colliders.
Thanks for the information! I'll get to playing around and see what I could!
Answer by EpiFouloux · Jun 14, 2016 at 12:17 PM
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[i]
}
Cool thanks for the reply, I was ai$$anonymous$$g at keeping it as close to how I'd started but like you guys said it might not be the best way.
Glad we could help :) can you accept my answer so we close the topic?