Search Unity

Unity scripting help

Discussion in 'Scripting' started by mrseve, Jun 15, 2018.

  1. mrseve

    mrseve

    Joined:
    Jun 15, 2018
    Posts:
    13
    Here's my problem:
    I have a Danger script and a GameManager script.
    My Game Manager script includes the health and maxHealth of my player.
    Now I would like to get access to the health of my player in the Danger script, but I don't know how to do this.
    In my Danger script, I want to write down if the health of my player is under 0, I want my player to die.

    In my Danger script, i already tried the health = GetComponent<GameManager>(); function.
    But as soon as I keep on editing my Danger script with (like if the health of my player is under 0), it won't work out. So that GetComponent function doesn't seem to work on here.

    Hope you guys understand my problem. And I'm kinda new to the programing language thing... anyone else has an idea how to get access to my health on GameManager?

    I looked up on the net, watched a couple of tutorials but it didn't solve my problem.
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
    Yes, GetComponent.

    GetComponent as you have it written says to look at the same gameobject your Danger script is on and find the GameManager. If it doesn't find it, it returns null.

    So if they aren't on the same object, you have to find it some other way. The other option is your create a public variable in your Danger script of type GameManager and drag and drop, then access through that variable. Or, you could make GameManager a singleton. Or, you could use FindWithTags call. There are tons of ways of doing it. But in the end, it's just getting a reference to the GameManager script and accessing values on it.
     
  3. johne5

    johne5

    Joined:
    Dec 4, 2011
    Posts:
    1,133
    Is health and max health public or private?
    In the danger script. Does it look like this? health = GetComponent<GameManager>().health; this would set a local
    It would also fail if the GameManager and Danger scripts are not on the same gameObject.

    Please post your code so we can better help.