- Home /
How to check if player has an object in inventory
So...after the player picks up an object(flashlight i.e.), it goes to the inventory. How to check if the player has flashlight in inventory so he can use it. If the player doesn't pick up flashlight, he can't use it.
And after that, how to add small texture (indicator) of flashlight that shows that you have picked up the flashlight.
Flashlight script (js) #pragma strict
var LightIntesity = 2.0;
var LightRange = 16.0;
var LightSpotAngle = 42.0;
var AudioFile1 : AudioClip;
var AudioFile2 : AudioClip;
bool CheckForItem (Item "Flaslight") {
if (inventory.Contains("Flashlight")) {return true;}
else {return false;}
}
function Start (){
light.intensity = LightIntesity;
light.range = LightRange;
light.spotAngle = LightSpotAngle;
}
function Update (){
if (Input.GetKeyDown(KeyCode.F)){
if (light.enabled == false){
light.enabled = true;
audio.clip = AudioFile1;
audio.Play();
}
else{
light.enabled = false;
audio.clip = AudioFile2;
audio.Play();
}
}
}
Pickup script (js) #pragma strict
public var keyGrab : AudioClip; // Audioclip to play when the key is picked up.
private var player : GameObject; // Reference to the player.
private var playerInventory : PlayerInventory; // Reference to the player's inventory.
function Awake ()
{
// Setting up the references.
player = GameObject.FindGameObjectWithTag("Player");
playerInventory = player.GetComponent(PlayerInventory);
}
function OnTriggerEnter (other : Collider)
{
// If the colliding gameobject is the player...
if(other.gameObject == player)
{
// ... play the clip at the position of the key...
AudioSource.PlayClipAtPoint(keyGrab, transform.position);
// ... the player has a key ...
playerInventory.hasKey = true;
// ... and destroy this gameobject.
Destroy(gameObject);
}
}
PlayerInventory (js) #pragma strict
public var hasKey : boolean;
It would probably help to see the PlayerInventory class. In there should be defined whether the user has a flashlight or not
Well... you have a has$$anonymous$$ey variable. How about adding a hasFlashlight variable to your inventory.
that still isn't the right answer...haha btw I did it on purpose
Answer by kei_kvaartz · Jan 15, 2014 at 06:32 PM
Without seeing any code, I would assume the inventory is kept as a List. In that case I would use something like:
bool CheckForItem (Item wantedItem) {
if (inventory.Contains(wantedItem)) {return true;}
else {return false;}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613130528im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Picking up an object 2 Answers
inventory system - change GUI.DrawTexture texture 3 Answers
Separate textures for identical objects? 1 Answer
How would I implement this game mechanic? 0 Answers
create a menu to change texture on a certain object 1 Answer