I wanted help with implementing a state which ends game

I want my game to end if the player picks up a key on map and finds the car a drives away to make a simple ending to the game. I am thinking of making a pickup for key that prompts up on the UI and then either when the player is in the proximity of the car the game ends or player presses “F” on the car to end the game.

How can I go about implementing this in game?

I am creating this directly in the post editor - so nothing’s tested and there may be typos - but here’s the gist:

The Player

Make a script called Mover.cs to move the player

public class Mover : MonoBehaviour
{
    [SerializeField] float _moveSpeed = 1f;

    private void Update()
    {
        var moveVector = Vector3.zero;
        moveVector += Vector3.right * Input.GetAxis("Horizontal");
        moveVector += Vector3.forward * Input.GetAxis("Vertical");
        moveVector = moveVector.normalized;

        transform.Translate(moveVector * _moveSpeed * Time.deltaTime);
    }
}

Add an empty game object to the scene, call it ‘Player’ and tag it with ‘Player’. Give it some visuals, a collider and a rigidbody. Make the rigidbody kinematic, and set gravity to 0. Put the Mover script on it.

Make a script called Player.cs to hold some player info

public class Player : MonoBehaviour
{
    private bool _hasKey = false;

    public bool HasKey() => _hasKey;
    public void SetHasKey() => _hasKey = true;
}

Put this script on the player game object. It will only hold whether the player has the key or not.

The Key

Make a script called KeyPickup.cs to detect when the player ‘picks it up’

public class KeyPickup : MonoBehaviour
{
    private void OnTriggerEnter(Collider other)
    {
        if (!other.CompareTag("Player")) return;
        if (!other.TryGetComponent<Player>(out Player player)) return;
        player.SetHasKey();
        Destroy(gameObject);
    }
}

Make a new game object and call it ‘Key’. Give it some visuals, and add a collider. Set the collider to trigger, and put the KeyPickup script on it.

The Car

Make a script called CarTrigger.cs to detect when the player is within range. You could use a collider, but I’ll do something different.

using UnityEngine.SceneManagement;
public class CarTrigger : MonoBehaviour
{
    [SerializeField] float _detectRadius  = 3f;
    [SerializeField] string _targetScene;

    private Player _player;

    private void Start() => _player = FindObjectOfType<Player>();

    private void LateUpdate()
    {
        if (!_player.HasKey()) return;
        if (Vector3.Distance(transform.position, _player.transform.position) > _detectRadius) return;

        SceneManager.LoadScene(_targetScene);
    }
}

Make a new game object and call it ‘Car’. Give it some visuals and put the CarTrigger script on it. Set your target scene and detect range.

Job’s done.


Edit
Oh, I forgot the UI

The UI

Make a script called KeyPickupUI.cs

public class KeyPickupUI : MonoBehaviour
{
    [SerializeField] Sprite _keySprite;

    private void Start() => _keySprite.enabled = false;

    public void SetHasKey() => _keySprite.enabled = true;
}

Make a new canvas game object, and add a Sprite to it. Give it a ‘key’ image. Put the KeyPickupUI script on the canvas and drag the sprite object into the Key Sprite field in the inspector.

Updates

We need to update the KeyPickup.cs script

public class KeyPickup : MonoBehaviour
{
    // Get a reference to the UI
    [SerializeField] KeyPickupUI _keyPickupUI;

    private void OnTriggerEnter(Collider other)
    {
        if (!other.CompareTag("Player")) return;
        if (!other.TryGetComponent<Player>(out Player player)) return;
        player.SetHasKey();
        // Add this line
        _keyPickupUI.SetHasKey();
        Destroy(gameObject);
    }
}

Drag the canvas into the Key Pickup UI field in the inspector

/Me: Made a game in 18 minutes…


Another Edit I seem to have misread your question, but the above should still be helpful

1 Like

In this block of code = both enabled has red squiggly lines under it and the error says

Severity Code Description Project File Line Suppression State
Error CS1061 ‘Sprite’ does not contain a definition for ‘enabled’ and no accessible extension method ‘enabled’ accepting a first argument of type ‘Sprite’ could be found (are you missing a using directive or an assembly reference?)

Oops, my bad. Should have been the Image (I’ve renamed the field, too)

public class KeyPickupUI : MonoBehaviour
{
    [SerializeField] Image _keyImage;

    private void Start() => _keyImage.enabled = false;

    public void SetHasKey() => _keyImage.enabled = true;
}

Happens when you ‘cowboy’ code into a text editor

1 Like

Ohk Soo after making all the change’s the code works great but the only thing is I don’t understand the code itself all i did was copy paste and trying to understand how the code is being executed. Other than that I am really great that code is working as I expected

I don’t know which code you took. I suspect you put this in your own game, so you don’t need everything, but I’ll go over everything quick:

This creates a vector from the player’s input. Horizontal is mapped to X axis, Vertical is mapped to Z axis. Then it adjusts it for speed and frame and moves the player by an amount. This is not very good movement code, but I think it should work.

This is a trigger on the key. When something enters the trigger (collides with it), the code checks if it is the player (has the “Player” tag). If it does, it tries to get the Player component and calls SetHasKey() on it. This will let us know that the player has the key. It also asks the UI to display the key image. It then destroys itself (because the player ‘picked it up’)

This is the car. On every frame, after the movement and stuff (Late Update), the car checks if the player has the key. If the player does have the key, it will check how far the player is from the car. If the player is within the detect range (proximity), it will load the scene specified. This may be the next level, or a ‘Win’ scene, or whatever

The UI is updated by the key pickup. When the script starts, it hides the key image. When the player ‘picks up’ the key, the UI is updated to display the image

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms