- Home /
The question is answered, right answer was accepted
I want to open loot chest prefabs individually in the scene
I have a loot chest created for my 3D game which has a trigger that detects when the player is standing in front of it & a bool which sets to true when the play stands in front of it. It works perfectly however when I drag another loot chest into the scene and try to open it, they both open. I get that they are both using the same script so makes sense that they would both open at the same time.
My question is what is the best way to set up my script so only the loot chest my player is standing in front of opens?
Answer by TheIrishKraken · May 15 at 06:10 AM
Here are both my scripts that are attached to the loot chest prefab
Answer by Caeser_21 · May 15 at 07:47 AM
They both are opening because they have the same reference script for chestTrigger
(As you said)
I don't think you need a separate script for checking whether the player is near or not... just add a TriggerCollider
to all the chests and combine both the scripts, Like this :
private bool isPlayerNearChest; //This is at the top of the script
//Add the rest of the script here but change the IF statement in the update function
private void OnTriggerEnter(Collider other)
{
if (other.transform.tag == "Player")
{
isPlayerNearChest = true;
}
}
private void OnTriggerExit(Collider other)
{
if (other.transform.tag == "Player")
{
isPlayerNearChest = false;
}
}
I just separated them for easier readability. The chest already has a trigger attached to it which is working with no issue, the problem is no matter which trigger I walk into it will open every chest in the scene as apposed to just the one I'm standing in front of. I just cant figure out the easiest way to manage this.
As per your script it seems like there is only one ChestTrigger
in the scene... You need one per chest and you have to change your script accordingly
Answer by TheIrishKraken · May 15 at 10:23 AM
There's two triggers in the scene, one per chest.
Ah I figured out what to do, the way I referenced the chest trigger was incorrect. I used chestTrigger = GetComponentInChildren(); instead in the Awake function.
This directly referenced the ChestTrigger that the player was standing in front of instead of finding all the ChestTriggers in the scene by finding their tag.
I do really appreciate you trying to help me however. :)
Follow this Question
Related Questions
How Can I load Different Prefab on Combobox Change? 0 Answers
How to load instances of a prefab to an array c# 2 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
PrefabUtility does not exist? 1 Answer