Search Unity

  1. Improved Prefab workflow (includes Nested Prefabs!), 2D isometric Tilemap and more! Get the 2018.3 Beta now.
    Dismiss Notice
  2. The Unity Pro & Visual Studio Professional Bundle gives you the tools you need to develop faster & collaborate more efficiently. Learn more.
    Dismiss Notice
  3. Let us know a bit about your interests, and if you'd like to become more directly involved. Take our survey!
    Dismiss Notice
  4. Improve your Unity skills with a certified instructor in a private, interactive classroom. Watch the overview now.
    Dismiss Notice
  5. Want to see the most recent patch releases? Take a peek at the patch release page.
    Dismiss Notice

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:
    3,976
    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,076
    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.