Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Global Variable

Discussion in 'Scripting' started by fredyyanez, Jul 10, 2014.

  1. fredyyanez

    fredyyanez

    Joined:
    Jul 8, 2014
    Posts:
    33
    I am able to get the object information in the Update function and I'm able to see the Vector3 using Debug.Log()..but I cannot get this updated information in the OnGUI() function is there a way to make the Vector3 into a global variable so I can access it in the OnGUI() function? Here is my code:

    using UnityEngine;
    using System.Collections;

    public class text : MonoBehaviour {
    public SimpleCloudHandler other;

    public Transform target;
    public static Vector3 screenPos;

    void Start(){
    }

    void Update () {

    Vector3 screenPos = camera.WorldToScreenPoint (target.position);
    Debug.Log(screenPos[0]);
    }

    void OnGUI() {
    GUI.Label (new Rect(screenPos[0],screenPos[1],screenPos[2],50), "" + other.TextFunc());
    Debug.Log(screenPos[0]);

    }
    }


    Im trying to make the Label follow a tracker that will be overlayed onto my target

    Thanks!
     
  2. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,398
  3. LightStriker

    LightStriker

    Joined:
    Aug 3, 2013
    Posts:
    2,716
    Code (csharp):
    1. void Update ()
    2. {
    3.     Vector3 screenPos = camera.WorldToScreenPoint (target.position);
    4.     Debug.Log(screenPos[0]);
    5. }
    The problem here is that you declare a new local variable, which is different from your class variable of the same name.

    Code (csharp):
    1. void Update ()
    2. {
    3.     screenPos = camera.WorldToScreenPoint (target.position);
    4.     Debug.Log(screenPos[0]);
    5. }
    By removing the type declaration, you use the class variable instead of defining new one.
     
    IvanAuda and fredyyanez like this.
  4. fredyyanez

    fredyyanez

    Joined:
    Jul 8, 2014
    Posts:
    33
    THANK YOU SO MUCHHHH! Your have no idea how happy I am!!! thanks!