Unlocking Doors with Keys [Scripts]

paulgswansonpaulgswanson Posts: 95Member
edited October 14 in Scripts & Mods
I know there's most likely an easier way to do this with the UFPS inventory system but I wasn't able to figure out how the heck to use it. Was tired of struggling with it...So I made my own key holder of sorts. Might as well Share what Iv got.
So its a 5 part script.
1 Storing the keys
2 A Bobbing Rotating Pickup Script
3 A Variable Trigger
4 Door Movement
5 And the Actual Key


I'll start with the key setup:
The first script is to make sure you have some where to put the key and its fairly simple.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PGS_SpecialGameVariables : MonoBehaviour
{
public static int Red_key;
public static int Blue_key;
public static int Green_key;
public static int Yellow_key;
public static int White_key;
public static int Black_key;
}
*Additive Note*
I realized this after the fact but I can use this script to also call values to save like player Position, Ammo's each key. Hahah this such a ghetto yet useful utility script
*/Additive Note*

All that does obviously is make a static int. When i start playing with this I decided I didn't wanna use Bools, just incase i wanted to make them consumable. That would have forced 1 key of each color. So I make them ints instead. Feel free to change it if you want.

Next part is make a New GameObject. I used a cube as my test. And put a Sphere collider on it larger than the shape was. You can use an actual key if you really want. I made mine red for easier testing purposes as you'll see in my code coming up.

Edit** Added sound options here too

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(AudioSource))]
public class PGS_AddRedKey : MonoBehaviour
{
[Header("Add the Player Objects Name.")]
public string PlayerObjectName;
public AudioClip GotKeySound;
private bool PlayAudio = true;
public bool _ShowDebug = true;
// On Collision with Game Object tagged Player add 1 Key
void OnTriggerEnter(Collider collider)
{
if (collider.gameObject.name == PlayerObjectName)
{
PGS_SpecialGameVariables.Red_key += 1;
if (PlayAudio == true)
{
AudioSource audio = GetComponent<AudioSource>();
audio.PlayOneShot(GotKeySound);
PlayAudio = false;
}
if (_ShowDebug == true)
{
Debug.Log("Got RedKey");
}
Destroy(gameObject);
}
}
}
You'll need a new script for each color key you want to use I went with 6 different colors.
So that's the first part. So make it work you need to is put in a string that matches your player object exactly. Colliders gave me issues trying to sense Tags because of the Players Trigger Volume.

If you want to make it float and bob you can use this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PGS_BobbingPickup : MonoBehaviour {
[Header("Amplitude is how far it will bob")]
public float amplitude; //Set in Inspector

[Header("Speed is how fast it will move")]
public float speed; //Set in Inspector

[Header("These will automatically set.")]
[Header("Exposed for tracking purposes")]
public float OriginPositionY;
public float OriginPositionX;
public float OriginPositionZ;
public Vector3 tempPos;

[Header("Rotation Speed Per Second.")]
[Header("For no rotation set to 0")]
public float zSpeed=0f; //degrees per second
public float xSpeed=0f; //degrees per second
public float ySpeed=.75f; //degrees per second

// Use this for initialization
void Start()
{
OriginPositionY = transform.position.y;
OriginPositionX = transform.position.x;
OriginPositionZ = transform.position.z;
}

// Update is called once per frame
void Update() {
{
tempPos.y = OriginPositionY + amplitude * Mathf.Sin(speed * Time.time);
tempPos.x = OriginPositionX;
tempPos.z = OriginPositionZ;
transform.position = tempPos;
transform.Rotate(xSpeed, ySpeed, zSpeed * Time.deltaTime); //rotation rates defined by 'xSpeed''ySpeed' and 'zSpeed'
}
}
}
All the other tutorials kept screwing around with Arrays or doors that only open in a certain order. All I wanted was if I have a red key it lets me open a red door. Just like needing new scripts for each key were you swap out the colors same with the doors, just replace red with whatever color you wanna use. Far from perfect I know. But it was good enough for me.

The next 2 scripts both go on the Door itself.

***Edit Made it play sound. :)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(AudioSource))]
public class PGS_RedDoor_Movement : MonoBehaviour
{
public GameObject Door;
[Header("How far are we moving")]
public int MoveDoorDistance;
public float MoveDoorSpeed;
public Vector3 _MoveTowards;
public AudioClip OpenDoorSound;
private bool PlayAudio=true;

// Update is called once per frame
void Update()
{
//will check if true and if it is then move door how far you defined in variables
if (gameObject.GetComponent<PGS_RedDoor_Trigger>().DoorIsUnlocked)
{
OpenDoor();
}
}
void OpenDoor()
{
if (PlayAudio == true)
{
AudioSource audio = GetComponent<AudioSource>();
audio.PlayOneShot(OpenDoorSound);
PlayAudio = false;
}
float step = MoveDoorSpeed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, _MoveTowards, step);
}
}
And now the last script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PGS_RedDoor_Trigger : MonoBehaviour
{
[Header("Add the Player Objects Name.")]
public string PlayerObjectName;
public bool DoorIsUnlocked = false;
public bool DoorIsLocked = true;
public bool ConsumeKey = false;
[Header("How many keys will it take")]
[Header("To Open the door?")]
public int Consumption = 1;
public bool _ConsumedDebugLog = true;
// Use this for initialization
// On Collision check if Player has specified Key
void OnTriggerEnter(Collider collider)
{
if (collider.gameObject.name == PlayerObjectName)
{
if (PGS_SpecialGameVariables.Red_key != 0) // On Collision check if Player has specified Key
{
DoorStatus();
}
}
}
// Call this when you want the door to open smoothly
private void DoorStatus()
{
DoorIsUnlocked = true;
DoorIsLocked = false;
if (ConsumeKey == true)
{
PGS_SpecialGameVariables.Red_key = PGS_SpecialGameVariables.Red_key - Consumption;
ConsumeKey = false;
if (_ConsumedDebugLog == true)
{
Debug.Log("Consumed Red Key");
Debug.Log(PGS_SpecialGameVariables.Red_key+" Remaining");
}
}
}
}

Comments

  • BrandSpankingNewBrandSpankingNew Posts: 2,321Member, MPTester
    That kind of "doing it this way" stuff is how you grow and gain muscle, is my feeling on the matter.

    I like the Castle Wolfenstein look of that scene! I kept expecting to see a big German shepherd come tearing around the corner, growling and snarling.

    I would think that you could store keys just as we now store grenades. Or various types of ammo.

    Then, because each type of door "knows" what kind of key it needs, I suppose you could quickly query the inventory for the existence of that specific key. I mean, just as ammo is sought when an attempt to reload a weapon occurs. You could then "consume" the key, or not, depending upon how you want things to behave. Anyhow, your way looks just fine to me.

    I mentioned grenades earlier because I use more than one type of grenade, but I think that treating the keys more like ammo, so that you don't have to actually wield them (just as ammo is never "really" seen or wielded) would probably be a better analogy. Looks great.
    Beautiful objects are wrought by study through effort, but ugly things are reaped automatically without toil.
    Democritus
  • paulgswansonpaulgswanson Posts: 95Member
    edited October 14
    Wow! I really appreciate the positive words @BrandSpankingNew . I'm still fairly new to reading/writeing code to this was my best effort to make something usable.
    *Note also in the Trigger script I just added a Bool to enable Consuming and a Public variable to define how many Keys it might take.

    I may once I finally get it to work properly replace this with a version that uses the UFPS inventory system. *Ya know using the hint you very graciously provided. I'm working this weekend ...stupid DR tests...So it certainly wont be tomorrow lol
Sign In or Register to comment.