Home > OS >  Referencing bool on another game object not working?
Referencing bool on another game object not working?

Time:12-04

I have a hitbox with a script called "accept", I then have 2 prefabs that have a public bool of "isPoor". One of the prefabs = true, the other = false.

When the prefabs with isPoor = true goes into the "accept" hitbox I want the game to fail, and when isPoor = false goes into "accept" hitbox I want the player to win.

The problem with the code I have is that it only ever fails the game, even when an NPC with isPoor = false goes into the "accept" hitbox.

This is the code for the accept hitbox.

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

public class accept : MonoBehaviour
{
    public LayerMask grabbable;
    public GameObject Spawner;
    bool isPoor;
    public GameManager gameManager;

    public void OnTriggerEnter2D(Collider2D other)
    {
        isPoor = other.gameObject.GetComponent<Poor>().isPoor;

        if (isPoor = true)
        {
            gameManager.GameOver();
        }

        if (isPoor = false)
        {
            gameManager.GameWon();
        }

        Destroy(other.gameObject);

        Spawner.GetComponent<Spawner>().Spawn();

    }

}

It's my first time using Unity so I'm a bit stumped. But it seems that the script just treats both prefabs as if they had isPoor = true.

CodePudding user response:

There is no point in making isPoor a field in class accept (which would store it for the entire lifetime of the object), since you are retrieving a new value anyway in OnTriggerEnter2D. Make it a local variable.

Then = is assignment, not comparison (you will get a warning for using = in Visual Studio). Use == for comparison. But for a Boolean this is not necessary. Just test like this:

// bool isPoor; drop this declaration!

public void OnTriggerEnter2D(Collider2D other)
{
    bool isPoor = other.gameObject.GetComponent<Poor>().isPoor;
    if (isPoor) {
        // isPoor == true here
        gameManager.GameOver();
    } else {
        // isPoor == false here
        gameManager.GameWon();
    }

    Destroy(other.gameObject);
    Spawner.GetComponent<Spawner>().Spawn();
}

Note that C# has the concept of the "assignment expression" which - besides doing the assignment - yields the assigned value, which is always true in your first if and always false in your second if.

CodePudding user response:

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

public class accept : MonoBehaviour
{
    public LayerMask grabbable;
    public GameObject Spawner;
    bool isPoor;
    public GameManager gameManager;

    public void OnTriggerEnter2D(Collider2D other)
    {

        if (other.gameObject.GetComponent<Poor>().isPoor)
            gameManager.GameOver();
        else
            gameManager.GameWon();

        Destroy(other.gameObject);

        Spawner.GetComponent<Spawner>().Spawn();

    }

}

  • Related