GetComponent Public Float

Hi,

I have a public float in one of my scripts that I need in another one of my scripts, I have used GetComponent to reference the script where the public float is, I just don’t know how to get this script to see the float. Can anyone help?

Look around, there are literally hundred of answers on that topic and probably a dozen with detailed explanation. Give Google a chance.

–

Hi, I did look around first, I looked on google and found lots of detailed explanations on it but they were so detailed they didn't make any sense to me. I found simpler explanations which I tried but could not get them to work. I thought I had found the solution when watching a Unity tutorial video, but I still kept getting errors. I even posted my project and the script on the Unity forums, which no one has yet replied to, which then led me to ask the question here and within 5mins the thread was closed, still without finding the answer.

–

1 Answer

1

Well if I understand correctly, here an example:

  1. attach each script to a gameobject in the hierachy
  2. then select the gameobject that has the scriptA
  3. and drag and drop it to the field in the scriptB (in the inspector)

Note: to do it: first select the scriptB, then click without releasing the scriptA (that way the scriptB will stay open on the inspector)

public class ScriptA : MonoBehaviour
    {
        public float myPublicFloat;
        
    }


public class ScriptB : MonoBehaviour
    {
        public ScriptA attachedScriptA;

        // Update is called once per frame
        void Update()
        {
            float damage = attachedScriptA.myPublicFloat * 9000;
            Debug.Log("Hit something with damage: " + damage);
        }
    }

Is that using GetComponent?

–

There is no need for GetComponent in this example as it is implied in the dragging process.

–