- Home /
Access a variable from another Script inside IF
Hey guys, how can I access a variable from another Script inside IF ?
I accessed a float variable on another script, and changed it, but I want to limit the value on this script, this is my script:
if (Input.GetKey(KeyCode.D) && apertou == true)
{
float water = GameObject.FindWithTag("Boia").GetComponent<Floater>().waterLevel += Time.deltaTime;
if (Input.GetKey(KeyCode.D) && apertou == true)
{
float water = GameObject.FindWithTag("Boia").GetComponent<Floater>().waterLevel += Time.deltaTime;
}
if ( water >= 6806 (or the right code to limit the variable waterLevel))
{
Debug.Log("go");
}
Answer by deltamish · Dec 11, 2012 at 01:30 PM
Hi, Its not actually possible to access a variable that is created under a function Because Unity only checks the variables that are created outside a function
Eg 1 Using Variables outside the function(void , if , else ..etc) Add both the script to the same object*Right Working Method*
using UnityEngine;
using System.Collections;
public class Test : MonoBehaviour {
public float x= 0;
public float y = 0;
void Update(){
if(Input.GetKeyDown(KeyCode.A)){
x++;//same as x+=1 ie adds 1 to the current number
}
if(Input.GetKeyDown(KeyCode.B)){
y++;
}
}
}
Getting value from other script an printing it
using UnityEngine;
using System.Collections;
public class ValueObtainer : MonoBehaviour {
void Update(){
float xvalue = transform.GetComponent(Test).x;
print(x);//or y your wish
}
}
now the same script with x and y variables inside the function Wrong method ,doesnot work
using UnityEngine;
using System.Collections;
public class Test : MonoBehaviour {
void Update(){
if(Input.GetKeyDown(KeyCode.A)){
flaot x+=1;//same as x+=1 ie adds 1 to the current number
}
if(Input.GetKeyDown(KeyCode.B)){
float y+=1;
}
}
}
Getting value from other script an printing it
using UnityEngine;
using System.Collections;
public class ValueObtainer : MonoBehaviour {
void Update(){
float xvalue = transform.GetComponent(Test).x;
print(x);//or y your wish
}
}
Here,since x and y values are inside a function,in this case "void and if"functions Unity returns value null
Your answer
Follow this Question
Related Questions
Accessing variable from a method in another script and gameObject 2 Answers
Can I access variables of scripts that inherit from abstract classes? 2 Answers
How to access variable from other class? 1 Answer
how to acess Static variable in other scripts without extended functions? 2 Answers
Can't access a javascript static variable from c# script 1 Answer