Search Unity

  1. Unity 2018.3 is now released.
    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. We've updated our Terms of Service. Please read our blog post from Unity CTO and Co-Founder Joachim Ante here
    Dismiss Notice
  4. Want to provide direct feedback to the Unity team? Join the Unity Advisory Panel.
    Dismiss Notice
  5. Improve your Unity skills with a certified instructor in a private, interactive classroom. Watch the overview now.
    Dismiss Notice

Unity scripting help

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

  1. mrseve


    Jun 15, 2018
    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


    Aug 12, 2014
    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


    Dec 4, 2011
    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.