- Home /
How do I take a public float from a different script and access it
So i have a public float health on one script and i need to call this float from another script. Please help Im lost :C
Answer by ShadyProductions · Jul 16, 2017 at 10:59 AM
Have you even bothered to look around? This question has been asked a million times before.
If your script is monobehaviour:
You can use GetComponent<ScriptName>().yourfloat
if the script is on the same object as your other script. Or find the object first with a tag using GameObject.FindWithTag("yourobject")
and then do .GetComponent<ScriptName>().yourfloat
if your script is not monobehaviour you will have to make a new instance like
yourscript script = new yourscript();
script.yourfloat
or make your float value static and you can do yourscript.yourfloat
without making a new instance.
its doing what i want but unty says
You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed. MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all UnityEngine.MonoBehaviour:.ctor () sfp:.ctor ()
Answer by Kaskorian · Jul 16, 2017 at 10:55 AM
you can write a public float function which returns the value and then you can call this function in another script
and if you want to Change it
public float SetHealth(float index) {health = index}
That still doesn't explain how to call it from another script, completely beside the point. Look my answer for a more detailed answer.
Your answer
Follow this Question
Related Questions
Getting a variable from another script 2 Answers
GetComponent C# 1 Answer
public float being defined as object? 2 Answers
How to make classes/structs public to all scripts 0 Answers
Multiple Cars not working 1 Answer