Make a variable usable outside of a function C#

I’m trying to make a variable, however it requires it to be made in the Start() function. I need to be able to reference it in the Update() function. How can you do this?

Define the variable at the class scope:

public class MyScript : MonoBehaviour
{

    public float Value;

    void Start()
    {
        Value = 5f;
    }

    void Update()
    {
        Value += Time.deltaTime;
    }

}

Just an example… but I’m referencing the same variable in both Start and Update.

I mean’t that I needed to assign its value in Start() and then use it in Update().

Your example gives a NullReferenceException.

I forgot to put in the ‘class’ in defining the class… I typed it into the browser… mistypes happen.

Though null reference shouldn’t happen… because it was malformed code.

And lastly… yes, in my example I assign it in the Start, and I use it in Update.

I already was testing it in a class. Here is my code (ignore some teleporting gltiches and stuff):

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class chase : MonoBehaviour {

    public GameObject targetPlayer = GameObject.Find ("player");
    public Transform target;
    public float radar = 12f;
    public float speed = 7;

    void Start(){
        target = targetPlayer.transform;
    }

    void Update () {
        Vector3 displacementFromTarget = target.position - transform.position;
        Vector3 directionToTarget = displacementFromTarget.normalized;
        Vector3 velocity = directionToTarget * speed;

        float distanceToTarget = displacementFromTarget.magnitude;

        if (distanceToTarget <= radar) {
            transform.Translate (velocity * Time.deltaTime);
        }
    }
}

Don’t call ‘GameObject.Find’ in a variable declaration.

Put that in ‘Start’ as well.

And lastly if a GameObject doesn’t exist with that name… you’ll get a null reference exception.

1 Like

Worked. Thanks!